MODULE -8
File Handling in C
Agenda
1 . Introduction to Files
2 .Types of files
3 .Using Files in C
4 .Reading data from files
5 .Writing data to files
6 .Detecting the End-of-File
7.Functions for selecting a record
randomly(File positioning)
8 .Error Handling during file operations
9 .Accepting Command line arguments
10.Renaming and Creating temporary file
Drawbacks of Traditional System
‱ Until now we are using Console Oriented I/O functions.
‱ “Console Application” means an application that has a text-based
interface. (black screen window)
‱ Most applications require a large amount of data , if this data is
entered through console then it will be quite time consuming task
‱ Main drawback of using Traditional I/O :- data is temporary (and
will not be available during re-execution )
File handling in C :
‱ New way of dealing with data is file handling.
‱ Data is stored onto the disk and can be retrieve whenever
require.
‱ Output of the program may be stored onto the disk
‱ In C we have many functions that deals with file handling
‱ Collection of byte may be interpreted as –
– Single character
MODULE 8-File and preprocessor.pptx for c program learners easy learning
MODULE 8-File and preprocessor.pptx for c program learners easy learning
Introduction to File
‱ A file is a collection of related data that a
computers treats as a single unit.
‱ Computers store files to secondary storage so
that the contents of files remain intact when a
computer shuts down.
‱ When a computer reads a file, it copies the file
from the storage device to memory; when it
writes to a file, it transfers data from memory
to the storage device.
‱ C uses a structure called FILE (defined in
stdio.h) to store the attributes of a file.
Types of Files
The types of files used can be broadly classified
into two categories:
1. Text File
contains ASCII codes that performs
read/write operations.
2. Binary File
can contain non-ASCII characters
Image, audio, video, executable, etc.
Using in files in C
To use files in C, we must use the following
steps:
1. Declaring a file pointer variable.
2. Open the file
3. Process the file.
4. Close the file.
Declaring a file pointer variable
‱ To access a particular file specify name of
the file that has to be used.
‱ This can be accomplished by using file
pointer variable.
‱ The syntax for declaring the file pointer is:
FILE
*file_pointer_name;
Ex: FILE *fp;
Opening a File
‱ We can use the fopen( ) function to create a new
file or to open an existing file.
‱ Following is the syntax of this function call:
‱ Using above prototype file whose pathname is
pointed to by filename is opened in mode
specified using the mode.
FILE *fopen( const char * filename, const char * mode );
File Modes
Code for opening a file
An error will be generated if you try to open a file that does not
exist.
FILE *fp;
fp=fopen(“student.txt”,”r”);
if(fp==NULL)
{
printf(“n the file could not be opened”);
exit(1);
}
Closing a File
‱ File must be closed as soon as all operations on
it completed
‱ Ensures
– All outstanding information associated with
file flushed out from buffers
– All links to file broken
– Accidental misuse of file prevented
Syntax: int fclose(file_pointer);
Ex:
FILE *p1, *p2;
p1 = fopen(“INPUT.txt”, “r”);
p2 =fopen(“OUTPUT.txt”, “w”);


..


..
fclose(p1);
fclose(p2);
Reading data from files
‱ C provides the following set of functions to
read data from a file:
 fscanf( )
 fgets( )
 fgetc( )
 fread( )
‱ fscanf( )
The fscanf() function is to read formatted data
from the stream.
‱ fscanf() is similar to the scanf() funtion except
that the first argument of fscanf() specifies a
stream from which to read,whereas scanf()
can only read from standard input
Syntax:
int fscanf( FILE *stream ,const char *format,
);
‱ fgets( )
The fgets() function is stands for file get string.this
function is used to get a stream.
Syntax:
‱ fgetc( )
The fgetc() function returns the next character
from stream and EOF if the end of file reached
or if there is an error
Syntax:
char *fgets( char *str ,int size,FILE *stream);
int fgetc(FILE *stream);
-
‱ fread( )
fread( ) function is used to read data from a file.
Syntax:
Remarks:
fread( ) reads a specified number of equal-sized data items
from an input stream into a block.
str = Points to a block into which data is read
size = Length of each item read, in bytes
num = Number of items read
stream = file pointer
int fread(void *str, size_t size, size_t num, FILE *stream);
#include<stdio.h>
#include<conio.h>
struct emp {
char name[10];
int age;
};
void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
while( !feof(q) )
{
fscanf(q,"%s %d", e.name, e.age);
printf("%s %d", e.name, e.age);
}
getch();
}
ABC
23
Writing data to files
‱ C provides the following set of functions to
writing data to a file:
 fprintf()
 fputc()
 fputs()
 fwrite()
‱ fprintf( )
The fprintf( ) function is to write formatted output
to the stream.
Syntax:
int fprintf( FILE *stream ,const char *format,
);
‱ fputs( )
The fputs( ) function is used to write a line to a file
Syntax:
‱ fputc( )
The fputc() function is used to write a character to
the stream.
Syntax:
int fputs( const char *str ,FILE *stream);
int fputc(int c, FILE *stream )
‱ fwrite()
fwrite() function is used to write data to a file.
Syntax:
Remarks:
fwrite() appends a specified number of equal-sized data
items to an output file.
str = Pointer to any object; the data written begins
at ptr
size = Length of each item of data
count =Number of data items to be appended
stream = file pointer
int fwrite(const void *str, size_t size, size_t count, FILE *stream);
‱ Simple program for reading/writing data from/to files:
#include <stdio.h>
int main ( )
{
FILE *outfile, *infile ;
int b = 5, f ;
float a = 13.72, c = 6.68, e, g ;
outfile = fopen ("testdata", "w") ;
fprintf (outfile, “ %f %d %f ", a, b, c) ;
fclose (outfile) ;
infile = fopen ("testdata", "r") ;
fscanf (infile,"%f %d %f", &e, &f, &g) ;
printf (“ %f %d %f n ", a, b, c) ;
printf (“ %f %d %f n ", e, f, g) ;
}
13.720000,5,6.680000
13.720000,5,6.680000
Detecting End-of-File
There are a number of ways to test for the end-of-file
condition. Another way is to use the value returned by
the fscanf () function.The prototype of feof() can be
given as :
int feof(FILE *fp);
Ex: FILE *fptr1;
int istatus ;
istatus = fscanf (fptr1, "%d", &var) ;
if ( istatus == feof(fptr1) )
{
printf ("End-of-file encountered.n”) ;
}
Error handling during file operation
‱ Typical errors that occur
– trying to read beyond end-of-file
– trying to use a file that has not been opened
– perform operation on file not permitted by ‘fopen’ mode
– open file with invalid filename
– write to write-protected file
‱ ferror()
The library function is used to check for error in the
stream.
‱ clearerr()
The function is used to clear EOF and error
indicator for the stream.
‱ perror()
It stands for print error.
Syntax: int ferror(FILE *stream)
Syntax: void clearerr(FILE *stream)
Syntax: void perror(const char *s)
‱ The following example shows the usage of perror( ) function.
#include <stdio.h>
#include <errno.h>
#include <string.h>
extern int errno ;
int main () {
FILE * pf;
int errnum;
pf = fopen ("unexist.txt", "rb");
if (pf == NULL) {
errnum = errno;
fprintf(stderr, "Value of errno: %dn", errno);
perror("Error printed by perror");
fprintf(stderr, "Error opening file: %sn", strerror( errnum ));
}
else {
fclose (pf) ;
}}
Output :
Error reading
from file
"file.txt"
Functions for selecting record
randomly
‱ Functions that are used to randomly access a
record stored in a binary file. This functions
include:
‱ fseek( )
‱ ftell( )
‱ rewind( )
‱ fgetpos( )
‱ fsetpos( )
‱ fseek()
The function fseek() reposition a binary stream.
‱ fseek() seeks the file position for stream; a subsequent read
or write will access data beginning at the new position.
‱ For a binary file, the position is set to offset characters from
origin, which may be
SEEK_SET (beginning),
SEEK_CUR (current position) or
SEEK_END (end of file).
For a text stream, offset must be zero, or a value returned by
ftell (in which case origin must be set to SEEK_SET).
‱ SEEK_SET,SEEK_CUR and SEEK_END are defined
constants with value 0,1 and respectively.
Syntax : int fseek(FILE *stream, long offset, int origin)
The following example shows the usage of
fseek() function.
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("D is not programming language", fp);
fseek( fp, 7, SEEK_SET );
fputs(" C Programming Language", fp);
fclose(fp);
return(0);
}
Output : C programming
language
‱ ftell( )
ftell( ) is used to find the current position of the file from
the beginning of the file.
‱ If successful, ftell() function returns the current
file position(in bytes) for stream.
‱ In case of error,ftell() returns -1.
‱ ftell() is useful when we have to deal with text
files for which position of the data cannot be
calculated.
Syntax: long int ftell(FILE *stream)
#include <stdio.h>
int main ()
{
FILE *fp;
int len;
fp = fopen("file.txt", "r");
if( fp == NULL )
{
perror ("Error opening file");
return(-1);
}
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fclose(fp);
printf("Total size of file.txt = %d bytesn", len);
return(0);
}
Let us assume we have a text file file.txt, which has the following
content −
This is tutorialspoint.com
Output : Total size of file.txt =
27 bytes
‱ rewind()
rewind() is used to reposition the file pointer to
the
beginning of the file.
‱ fgetpos()
fgetpos() records the file position in stream in
*pos, for subsequent use. The type fpos_t is
suitable for recording such values.
Syntax: void rewind(FILE *stream)
rewind is equivalent to fseek(fp, OL, SEEK_SET);
Syntax: int fgetpos(FILE *stream, fpos_t*pos)
‱ fsetpos()
fsetpos() positions stream at the position recorded by
fgetpos in *pos.
‱ remove()
The remove() function,as the name suggest is
used to erase a file.
Syntax : int fsetpos(FILE *stream,const fpos_t *pos)
Syntax: int remove (const char *filename);
Command Line arguments
‱ Command line arguments are given after name of
program in command line operating system such as
DOS or LINUX and are passed into the program
from the operating system.
main ( int argc, char *argv[])
‱ argc – gives a count of number of arguments
(including program name)
‱ char *argv[] defines an array of pointers to character
(or array of strings)
‱ argv[0] – program name
‱ argv[1] to argv[argc -1] give the other arguments as
strings
Renaming a file
‱ rename( )
The function rename( ) as the name suggests is
used to rename a file.
If the oldname specifies pathname of a file that is
not directory,the new name shall also not point
to the pathname of a directory.
Syntax: int rename(const char *old name,const
char * new name)
Example:
#include <stdio.h>
int main ()
{
int ret;
char oldname[] = "file.txt";
char newname[] = "newfile.txt";
ret = rename(oldname, newname);
if(ret == 0)
{
printf("File renamed successfully");
}
else
{
printf("Error: unable to rename the file");
}
return(0);
}
Output: File renamed
successfully
Creating a Temporary file
‱ tmpfile()
The tmpfile() function is used to create a temporary
file.
A file created with tmpfile() will be automatically
deleted when all references to the file are closed.
On success,tmpfile( ) will return a pointer to the
stream of the file name that is created.
Syntax: FILE*tmpfile(void);
The following example shows the usage of tmpfile()
function.
#include <stdio.h>
int main ()
{
FILE *fp;
fp = tmpfile();
printf("Temporary file createdn");
/* you can use tmp file here */
fclose(fp);
return(0);
}
Output: Temporary file
created
Preprocessor Directives
Introduction
‱ The C Preprocessor is not a part of the compiler,
but is a separate step in the compilation process.
Three kinds of directives
‱ File inclusion
– #include
‱ Macros
– #define
‱ Conditional compilation
– #if, #ifdef, #ifndef, #elif, #else, #endif
 Always starts with a line with “#”
 Can appear anywhere in a program
MODULE 8-File and preprocessor.pptx for c program learners easy learning
File Inclusion
‱ Allow a program or a module’s implementation to use certain
header file.
‱ An interface or a header file contains declarations for a
module
‱ Name of the header file should end in .h
‱ User-define header files “ ... ”
#include “sample.h”
‱ System header files: < ... >
#include <stdio.h>
Ex: /* program to call the function defined in “sample.c” file */
#include<stdio.h>
#include<conio.h>
#include “sample.c”
void main ( )
{
clrscr ( );
display ( );
}
Output: welcome to c
‱ /* file sample.c*/
int display( )
{
printf(“welcome to c”);
return 0;
}
Macro Substitution
 Provide parameterized text substitution
 The syntax of #define directive is as follows
Example : #define MAXLINE 120
#define lower(c) ((c)-`A’+‘a’)
 Macro replacement
char buf[MAXLINE+1];
becomes
char buf[120+1];
 c = lower(buf[i]);
becomes
c = ((buf[i])-`A’+‘a’);
#define identifier <substitute text>
Macros: Use “(“ and “)”
 Always parenthesize macro parameters in definition
#define plusone(x) x+1
i = 3*plusone(2);
becomes
i = 3*2+1
#define plusone(x) ((x)+1)
i = 3*plusone(2);
becomes
i = 3*((2)+1)
Conditional Compilation
 One source for many platforms or many cases
 Need to have special source for specific situations
 Conditional compilation
#ifdef <identifier>
#ifndef <identifier>
#if <expr>
#elif <expr>
#else
#endif
 Removing macro definitions
#undef <identifier>
‱ The syntax of the #ifdef directive is:
#ifdef <identifier>
{
statements1;
statements2;
}
#else
{
statements3;
statements4;
}
#endif
‱ Example: /* program to use conditional compilation statement to
check identifier is defined or not */
#include<stdio.h>
#include<conio.h>
#define LINE 1
void main ( )
{
clrscr ( );
#ifdef LINE
printf(“ This is line number one”);
#else
printf(“ This is line number two”);
#endif
getch( );
}
Output: This
is line
number one
The #ifndef directive
The syntax of the #ifndef directive is given below:
‱
#ifndef <identifier>
{
statements1;
statements2;
}
#else
{
statements3;
statements4;
}
#endif
Ex: /* program to use conditional compilation directive
#ifndef */
‱
#include<stdio.h>
#include<conio.h>
#define LINE
void main ( )
{
clrscr ( );
#ifndef LINE
printf(“ Macro is not defined”);
#else
printf(“Macro is defined”);
#endif
getch( );
}
Output: Macro is not
defined
Use of #if, #elif, #else and #endif
The preprocessor directives #if, #elif, #else and #endif allows to
conditionally compile a block of code based on predefined symbols.
Example: Program to illustrate this concept.
#include<stdio.h>
#define MAX 100
void main()
{
#if(MAX)
printf("MAX is defined");
#else
printf ("MAX is not defined");
#endif
}
Output:
MAX is defined
POINTERS 56
ANY
QUERIES??
MODULE 8-File and preprocessor.pptx for c program learners easy learning

More Related Content

PPTX
want to learn files,then just use this ppt to learn
PPTX
File in C language
PPT
File handling-c
PPT
File handling in c
PDF
Module 03 File Handling in C
PPTX
File Handling ppt.pptx shjd dbkd z bdjdb d
PPTX
File handling in c
PPTX
C Programming Unit-5
want to learn files,then just use this ppt to learn
File in C language
File handling-c
File handling in c
Module 03 File Handling in C
File Handling ppt.pptx shjd dbkd z bdjdb d
File handling in c
C Programming Unit-5

Similar to MODULE 8-File and preprocessor.pptx for c program learners easy learning (20)

PPTX
Programming in C
PPTX
pre processor and file handling in c language ppt
PPTX
C-Programming File-handling-C.pptx
 
PPTX
C-Programming File-handling-C.pptx
 
PPTX
PPS-II UNIT-5 PPT.pptx
PPT
File handling
PDF
File Handling in C Programming
PPTX
file handling in c programming with file functions
PDF
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
PDF
Module 5 file cp
PDF
637225560972186380.pdf
DOCX
Understanding c file handling functions with examples
PPTX
PPS PPT 2.pptx
PDF
14. fiile io
PPTX
File handling in c
PDF
VIT351 Software Development VI Unit5
PPT
Unit5
PPTX
File management
PPTX
Programming C- File Handling , File Operation
PPTX
File Handling in C.pptx
Programming in C
pre processor and file handling in c language ppt
C-Programming File-handling-C.pptx
 
C-Programming File-handling-C.pptx
 
PPS-II UNIT-5 PPT.pptx
File handling
File Handling in C Programming
file handling in c programming with file functions
EASY UNDERSTANDING OF FILES IN C LANGUAGE.pdf
Module 5 file cp
637225560972186380.pdf
Understanding c file handling functions with examples
PPS PPT 2.pptx
14. fiile io
File handling in c
VIT351 Software Development VI Unit5
Unit5
File management
Programming C- File Handling , File Operation
File Handling in C.pptx
Ad

Recently uploaded (20)

PPTX
CYBER SECURITY the Next Warefare Tactics
PPTX
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx
PDF
Votre score augmente si vous choisissez une catégorie et que vous rédigez une...
PPTX
(Ali Hamza) Roll No: (F24-BSCS-1103).pptx
PPTX
Pilar Kemerdekaan dan Identi Bangsa.pptx
PDF
Jean-Georges Perrin - Spark in Action, Second Edition (2020, Manning Publicat...
PPTX
STERILIZATION AND DISINFECTION-1.ppthhhbx
PDF
Capcut Pro Crack For PC Latest Version {Fully Unlocked 2025}
PPTX
DS-40-Pre-Engagement and Kickoff deck - v8.0.pptx
PDF
Data Engineering Interview Questions & Answers Batch Processing (Spark, Hadoo...
PPTX
New ISO 27001_2022 standard and the changes
PDF
Introduction to Data Science and Data Analysis
PDF
Optimise Shopper Experiences with a Strong Data Estate.pdf
PPTX
Steganography Project Steganography Project .pptx
 
PPTX
Introduction to Inferential Statistics.pptx
PPTX
Lesson-01intheselfoflifeofthekennyrogersoftheunderstandoftheunderstanded
PPTX
chrmotography.pptx food anaylysis techni
PPTX
modul_python (1).pptx for professional and student
PDF
Microsoft Core Cloud Services powerpoint
PDF
Tetra Pak Index 2023 - The future of health and nutrition - Full report.pdf
 
CYBER SECURITY the Next Warefare Tactics
sac 451hinhgsgshssjsjsjheegdggeegegdggddgeg.pptx
Votre score augmente si vous choisissez une catégorie et que vous rédigez une...
(Ali Hamza) Roll No: (F24-BSCS-1103).pptx
Pilar Kemerdekaan dan Identi Bangsa.pptx
Jean-Georges Perrin - Spark in Action, Second Edition (2020, Manning Publicat...
STERILIZATION AND DISINFECTION-1.ppthhhbx
Capcut Pro Crack For PC Latest Version {Fully Unlocked 2025}
DS-40-Pre-Engagement and Kickoff deck - v8.0.pptx
Data Engineering Interview Questions & Answers Batch Processing (Spark, Hadoo...
New ISO 27001_2022 standard and the changes
Introduction to Data Science and Data Analysis
Optimise Shopper Experiences with a Strong Data Estate.pdf
Steganography Project Steganography Project .pptx
 
Introduction to Inferential Statistics.pptx
Lesson-01intheselfoflifeofthekennyrogersoftheunderstandoftheunderstanded
chrmotography.pptx food anaylysis techni
modul_python (1).pptx for professional and student
Microsoft Core Cloud Services powerpoint
Tetra Pak Index 2023 - The future of health and nutrition - Full report.pdf
 
Ad

MODULE 8-File and preprocessor.pptx for c program learners easy learning

  • 2. Agenda 1 . Introduction to Files 2 .Types of files 3 .Using Files in C 4 .Reading data from files 5 .Writing data to files 6 .Detecting the End-of-File 7.Functions for selecting a record randomly(File positioning) 8 .Error Handling during file operations 9 .Accepting Command line arguments 10.Renaming and Creating temporary file
  • 3. Drawbacks of Traditional System ‱ Until now we are using Console Oriented I/O functions. ‱ “Console Application” means an application that has a text-based interface. (black screen window) ‱ Most applications require a large amount of data , if this data is entered through console then it will be quite time consuming task ‱ Main drawback of using Traditional I/O :- data is temporary (and will not be available during re-execution )
  • 4. File handling in C : ‱ New way of dealing with data is file handling. ‱ Data is stored onto the disk and can be retrieve whenever require. ‱ Output of the program may be stored onto the disk ‱ In C we have many functions that deals with file handling ‱ Collection of byte may be interpreted as – – Single character
  • 7. Introduction to File ‱ A file is a collection of related data that a computers treats as a single unit. ‱ Computers store files to secondary storage so that the contents of files remain intact when a computer shuts down. ‱ When a computer reads a file, it copies the file from the storage device to memory; when it writes to a file, it transfers data from memory to the storage device. ‱ C uses a structure called FILE (defined in stdio.h) to store the attributes of a file.
  • 8. Types of Files The types of files used can be broadly classified into two categories: 1. Text File contains ASCII codes that performs read/write operations. 2. Binary File can contain non-ASCII characters Image, audio, video, executable, etc.
  • 9. Using in files in C To use files in C, we must use the following steps: 1. Declaring a file pointer variable. 2. Open the file 3. Process the file. 4. Close the file.
  • 10. Declaring a file pointer variable ‱ To access a particular file specify name of the file that has to be used. ‱ This can be accomplished by using file pointer variable. ‱ The syntax for declaring the file pointer is: FILE *file_pointer_name; Ex: FILE *fp;
  • 11. Opening a File ‱ We can use the fopen( ) function to create a new file or to open an existing file. ‱ Following is the syntax of this function call: ‱ Using above prototype file whose pathname is pointed to by filename is opened in mode specified using the mode. FILE *fopen( const char * filename, const char * mode );
  • 13. Code for opening a file An error will be generated if you try to open a file that does not exist. FILE *fp; fp=fopen(“student.txt”,”r”); if(fp==NULL) { printf(“n the file could not be opened”); exit(1); }
  • 14. Closing a File ‱ File must be closed as soon as all operations on it completed ‱ Ensures – All outstanding information associated with file flushed out from buffers – All links to file broken – Accidental misuse of file prevented
  • 15. Syntax: int fclose(file_pointer); Ex: FILE *p1, *p2; p1 = fopen(“INPUT.txt”, “r”); p2 =fopen(“OUTPUT.txt”, “w”); 

.. 

.. fclose(p1); fclose(p2);
  • 16. Reading data from files ‱ C provides the following set of functions to read data from a file:  fscanf( )  fgets( )  fgetc( )  fread( )
  • 17. ‱ fscanf( ) The fscanf() function is to read formatted data from the stream. ‱ fscanf() is similar to the scanf() funtion except that the first argument of fscanf() specifies a stream from which to read,whereas scanf() can only read from standard input Syntax: int fscanf( FILE *stream ,const char *format,
);
  • 18. ‱ fgets( ) The fgets() function is stands for file get string.this function is used to get a stream. Syntax: ‱ fgetc( ) The fgetc() function returns the next character from stream and EOF if the end of file reached or if there is an error Syntax: char *fgets( char *str ,int size,FILE *stream); int fgetc(FILE *stream); -
  • 19. ‱ fread( ) fread( ) function is used to read data from a file. Syntax: Remarks: fread( ) reads a specified number of equal-sized data items from an input stream into a block. str = Points to a block into which data is read size = Length of each item read, in bytes num = Number of items read stream = file pointer int fread(void *str, size_t size, size_t num, FILE *stream);
  • 20. #include<stdio.h> #include<conio.h> struct emp { char name[10]; int age; }; void main() { struct emp e; FILE *p,*q; p = fopen("one.txt", "a"); q = fopen("one.txt", "r"); printf("Enter Name and Age"); scanf("%s %d", e.name, &e.age); fprintf(p,"%s %d", e.name, e.age); fclose(p); while( !feof(q) ) { fscanf(q,"%s %d", e.name, e.age); printf("%s %d", e.name, e.age); } getch(); } ABC 23
  • 21. Writing data to files ‱ C provides the following set of functions to writing data to a file:  fprintf()  fputc()  fputs()  fwrite()
  • 22. ‱ fprintf( ) The fprintf( ) function is to write formatted output to the stream. Syntax: int fprintf( FILE *stream ,const char *format,
);
  • 23. ‱ fputs( ) The fputs( ) function is used to write a line to a file Syntax: ‱ fputc( ) The fputc() function is used to write a character to the stream. Syntax: int fputs( const char *str ,FILE *stream); int fputc(int c, FILE *stream )
  • 24. ‱ fwrite() fwrite() function is used to write data to a file. Syntax: Remarks: fwrite() appends a specified number of equal-sized data items to an output file. str = Pointer to any object; the data written begins at ptr size = Length of each item of data count =Number of data items to be appended stream = file pointer int fwrite(const void *str, size_t size, size_t count, FILE *stream);
  • 25. ‱ Simple program for reading/writing data from/to files: #include <stdio.h> int main ( ) { FILE *outfile, *infile ; int b = 5, f ; float a = 13.72, c = 6.68, e, g ; outfile = fopen ("testdata", "w") ; fprintf (outfile, “ %f %d %f ", a, b, c) ; fclose (outfile) ; infile = fopen ("testdata", "r") ; fscanf (infile,"%f %d %f", &e, &f, &g) ; printf (“ %f %d %f n ", a, b, c) ; printf (“ %f %d %f n ", e, f, g) ; } 13.720000,5,6.680000 13.720000,5,6.680000
  • 26. Detecting End-of-File There are a number of ways to test for the end-of-file condition. Another way is to use the value returned by the fscanf () function.The prototype of feof() can be given as : int feof(FILE *fp); Ex: FILE *fptr1; int istatus ; istatus = fscanf (fptr1, "%d", &var) ; if ( istatus == feof(fptr1) ) { printf ("End-of-file encountered.n”) ; }
  • 27. Error handling during file operation ‱ Typical errors that occur – trying to read beyond end-of-file – trying to use a file that has not been opened – perform operation on file not permitted by ‘fopen’ mode – open file with invalid filename – write to write-protected file
  • 28. ‱ ferror() The library function is used to check for error in the stream. ‱ clearerr() The function is used to clear EOF and error indicator for the stream. ‱ perror() It stands for print error. Syntax: int ferror(FILE *stream) Syntax: void clearerr(FILE *stream) Syntax: void perror(const char *s)
  • 29. ‱ The following example shows the usage of perror( ) function. #include <stdio.h> #include <errno.h> #include <string.h> extern int errno ; int main () { FILE * pf; int errnum; pf = fopen ("unexist.txt", "rb"); if (pf == NULL) { errnum = errno; fprintf(stderr, "Value of errno: %dn", errno); perror("Error printed by perror"); fprintf(stderr, "Error opening file: %sn", strerror( errnum )); } else { fclose (pf) ; }} Output : Error reading from file "file.txt"
  • 30. Functions for selecting record randomly ‱ Functions that are used to randomly access a record stored in a binary file. This functions include: ‱ fseek( ) ‱ ftell( ) ‱ rewind( ) ‱ fgetpos( ) ‱ fsetpos( )
  • 31. ‱ fseek() The function fseek() reposition a binary stream. ‱ fseek() seeks the file position for stream; a subsequent read or write will access data beginning at the new position. ‱ For a binary file, the position is set to offset characters from origin, which may be SEEK_SET (beginning), SEEK_CUR (current position) or SEEK_END (end of file). For a text stream, offset must be zero, or a value returned by ftell (in which case origin must be set to SEEK_SET). ‱ SEEK_SET,SEEK_CUR and SEEK_END are defined constants with value 0,1 and respectively. Syntax : int fseek(FILE *stream, long offset, int origin)
  • 32. The following example shows the usage of fseek() function. #include <stdio.h> int main () { FILE *fp; fp = fopen("file.txt","w+"); fputs("D is not programming language", fp); fseek( fp, 7, SEEK_SET ); fputs(" C Programming Language", fp); fclose(fp); return(0); } Output : C programming language
  • 33. ‱ ftell( ) ftell( ) is used to find the current position of the file from the beginning of the file. ‱ If successful, ftell() function returns the current file position(in bytes) for stream. ‱ In case of error,ftell() returns -1. ‱ ftell() is useful when we have to deal with text files for which position of the data cannot be calculated. Syntax: long int ftell(FILE *stream)
  • 34. #include <stdio.h> int main () { FILE *fp; int len; fp = fopen("file.txt", "r"); if( fp == NULL ) { perror ("Error opening file"); return(-1); } fseek(fp, 0, SEEK_END); len = ftell(fp); fclose(fp); printf("Total size of file.txt = %d bytesn", len); return(0); } Let us assume we have a text file file.txt, which has the following content − This is tutorialspoint.com Output : Total size of file.txt = 27 bytes
  • 35. ‱ rewind() rewind() is used to reposition the file pointer to the beginning of the file. ‱ fgetpos() fgetpos() records the file position in stream in *pos, for subsequent use. The type fpos_t is suitable for recording such values. Syntax: void rewind(FILE *stream) rewind is equivalent to fseek(fp, OL, SEEK_SET); Syntax: int fgetpos(FILE *stream, fpos_t*pos)
  • 36. ‱ fsetpos() fsetpos() positions stream at the position recorded by fgetpos in *pos. ‱ remove() The remove() function,as the name suggest is used to erase a file. Syntax : int fsetpos(FILE *stream,const fpos_t *pos) Syntax: int remove (const char *filename);
  • 37. Command Line arguments ‱ Command line arguments are given after name of program in command line operating system such as DOS or LINUX and are passed into the program from the operating system. main ( int argc, char *argv[]) ‱ argc – gives a count of number of arguments (including program name) ‱ char *argv[] defines an array of pointers to character (or array of strings) ‱ argv[0] – program name ‱ argv[1] to argv[argc -1] give the other arguments as strings
  • 38. Renaming a file ‱ rename( ) The function rename( ) as the name suggests is used to rename a file. If the oldname specifies pathname of a file that is not directory,the new name shall also not point to the pathname of a directory. Syntax: int rename(const char *old name,const char * new name)
  • 39. Example: #include <stdio.h> int main () { int ret; char oldname[] = "file.txt"; char newname[] = "newfile.txt"; ret = rename(oldname, newname); if(ret == 0) { printf("File renamed successfully"); } else { printf("Error: unable to rename the file"); } return(0); } Output: File renamed successfully
  • 40. Creating a Temporary file ‱ tmpfile() The tmpfile() function is used to create a temporary file. A file created with tmpfile() will be automatically deleted when all references to the file are closed. On success,tmpfile( ) will return a pointer to the stream of the file name that is created. Syntax: FILE*tmpfile(void);
  • 41. The following example shows the usage of tmpfile() function. #include <stdio.h> int main () { FILE *fp; fp = tmpfile(); printf("Temporary file createdn"); /* you can use tmp file here */ fclose(fp); return(0); } Output: Temporary file created
  • 43. Introduction ‱ The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process.
  • 44. Three kinds of directives ‱ File inclusion – #include ‱ Macros – #define ‱ Conditional compilation – #if, #ifdef, #ifndef, #elif, #else, #endif  Always starts with a line with “#”  Can appear anywhere in a program
  • 46. File Inclusion ‱ Allow a program or a module’s implementation to use certain header file. ‱ An interface or a header file contains declarations for a module ‱ Name of the header file should end in .h ‱ User-define header files “ ... ” #include “sample.h” ‱ System header files: < ... > #include <stdio.h>
  • 47. Ex: /* program to call the function defined in “sample.c” file */ #include<stdio.h> #include<conio.h> #include “sample.c” void main ( ) { clrscr ( ); display ( ); } Output: welcome to c ‱ /* file sample.c*/ int display( ) { printf(“welcome to c”); return 0; }
  • 48. Macro Substitution  Provide parameterized text substitution  The syntax of #define directive is as follows Example : #define MAXLINE 120 #define lower(c) ((c)-`A’+‘a’)  Macro replacement char buf[MAXLINE+1]; becomes char buf[120+1];  c = lower(buf[i]); becomes c = ((buf[i])-`A’+‘a’); #define identifier <substitute text>
  • 49. Macros: Use “(“ and “)”  Always parenthesize macro parameters in definition #define plusone(x) x+1 i = 3*plusone(2); becomes i = 3*2+1 #define plusone(x) ((x)+1) i = 3*plusone(2); becomes i = 3*((2)+1)
  • 50. Conditional Compilation  One source for many platforms or many cases  Need to have special source for specific situations  Conditional compilation #ifdef <identifier> #ifndef <identifier> #if <expr> #elif <expr> #else #endif  Removing macro definitions #undef <identifier>
  • 51. ‱ The syntax of the #ifdef directive is: #ifdef <identifier> { statements1; statements2; } #else { statements3; statements4; } #endif
  • 52. ‱ Example: /* program to use conditional compilation statement to check identifier is defined or not */ #include<stdio.h> #include<conio.h> #define LINE 1 void main ( ) { clrscr ( ); #ifdef LINE printf(“ This is line number one”); #else printf(“ This is line number two”); #endif getch( ); } Output: This is line number one
  • 53. The #ifndef directive The syntax of the #ifndef directive is given below: ‱ #ifndef <identifier> { statements1; statements2; } #else { statements3; statements4; } #endif
  • 54. Ex: /* program to use conditional compilation directive #ifndef */ ‱ #include<stdio.h> #include<conio.h> #define LINE void main ( ) { clrscr ( ); #ifndef LINE printf(“ Macro is not defined”); #else printf(“Macro is defined”); #endif getch( ); } Output: Macro is not defined
  • 55. Use of #if, #elif, #else and #endif The preprocessor directives #if, #elif, #else and #endif allows to conditionally compile a block of code based on predefined symbols. Example: Program to illustrate this concept. #include<stdio.h> #define MAX 100 void main() { #if(MAX) printf("MAX is defined"); #else printf ("MAX is not defined"); #endif } Output: MAX is defined