Вы находитесь на странице: 1из 33

C Programming

File I/O in C

1
Unit Plan
• Understand the need for File I/O

• Classification of File I/O Functions

• Understanding Streams

• Various Functions for High Level I/O


– Functions for character I/O, string I/O and block I/O

• Command Line Arguments

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 2
Version No: 2.0

2
Need for File I/O
• Data that outlives the program needs to be stored in a permanent storage so
that it can be referred later.

• For example, a word processing application might save the text in a linked list
or some other data structure when the application is running, but when the
application is closed the contents of the linked list need to stored in a file.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 3
Version No: 2.0

3
Need for File I/O
• The C Language has no provision for file I/O. The developers of a C compilers
write several functions for I/O and make it available as a I/O library.

• The functions in the I/O library take assistance from the corresponding I/O
function’s provided by the underlying operating system.

• These functions in the I/O library are not a part of C’s formal definition but they
have become a standard feature of C Language.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 4
Version No: 2.0

4
Classification of File I/O functions

File I/O functions

High Level I/O functions Low Level I/O functions

Text I/O functions Binary I/O functions

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 5
Version No: 2.0

File I/O in C
The treatment of files in ‘C’ is very simple, unlike other programming
languages where there are special built in and often rigid file handling
routines. “C” treats a file as stream of characters and accordingly allows input-
output in streams of characters. File input-output is treated in much the same
way as input-output from the terminal and provides functions similar to those
provided for input-output from the terminal.

Classification of File I/O functions


High level I/O functions are more commonly used in a c program as compared
to low level I/O functions.
High level I/O functions are self sufficient as they take care of buffer
management. Whereas in case of low level I/O functions the buffer
management has to be done by the programmer.
Text I/O functions open files in text mode whereas binary I/O functions open
files in binary mode.

5
Understanding Streams
• The C Language I/O system provides a consistent interface to the programmer
independent of the actual I/O device used.

• C provides a level of abstraction between the programmer and the I/O device.
This abstraction is called as a stream.

• Stream is a logical connection to a file, screen , keyboard, and various other


I/O devises.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 6
Version No: 2.0

6
Understanding Streams (Contd…)
Illustrating a stream

Output Stream

C Program
Disk File

Input Stream

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 7
Version No: 2.0

• Understanding Streams
If a C Program has to write some data to a disk file, a output stream
corresponding to the disk file will be created. The C program will write the
data to this output stream and the operating system will write it to the disk
file. Similarly if a C Program has to read some data from a disk file, a input
stream corresponding to the disk file will be created. The data will be read
from the disk file to the input stream by the operating system and the C
program will read the data from the stream.This same approach is used
for any kind of I/O Device (ie screen, keybord, ports etc)

There are predefined streams for the standard I/O devices which are listed
below
1. stdin is a predefined stream for the standard input device which could be a
keyboard.
2. stdout is a predefined stream for the standard output device which could
be a monitor.
3. stderr is a predefined stream for the standard error device which could be
a monitor.
4. stdprn is a predefined stream for the standard printing device which could
be a parallel prnter.
5. Stdaux is a predefined stream for the standard auxiliary device which
could be a serial port.

7
Understanding Streams (Contd…)
• There are 2 types of streams
– Text stream (stream of ASCII characters)
– Binary stream (stream of bytes)

• C has a inbuilt structure FILE which represents a the logical stream.

• This structure has a buffer

• Whenever a C Program interacts with a disk file it creates a variable of


structure FILE.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 8
Version No: 2.0

8
File Opening Modes
Mode Description

“r” Searches file. If the file exists, loads it into memory and sets up a pointer which
points to the first character in it. If the file doesn’t exists it returns a null.
Operations possible - reading from the files

“w” Searches file. If the file exists, contents are overwritten. If the file doesn’t exists
a new file is created. Returns a null if unable to open the file.
Operations possible - writing to the file.

“a” Searches file. If the file exists, loads it into memory and sets up a pointer which
points to the first character in it. If the file doesn’t exists a new file is created.
Returns a null if unable to open the file.
Operations possible - appending new contents at the end of the file.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 9
Version No: 2.0

9
File Opening Modes (Contd...)
Mode Description

“r” Same as “r”


Operations possible – reading existing contents, writing new contents,
modifying existing contents of the file.

“w” Same as “w”


Operations possible – writing new contents, reading them back and modifying
existing contents of the file.

“a” Same as “a”


Operations possible – reading existing contents, appending new contents to
the end of file, cannot modify existing contents of the file.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 10
Version No: 2.0

10
High Level I/O functions

• Functions to open a File.


– fopen() is the function to open a file and its prototype is FILE *fopen (char *name,
char *mode);

– fopen() establishes a link between the program and the operating system.

– The first argument specifies the file name and the second argument specifies the
mode in which the file has to be opened.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 11
Version No: 2.0

11
High Level I/O functions (Contd…)

• Functions to open a File.


– If the file is found at the specified location then fopen() creates a variable of type
FILE structure and returns a pointer to it. This pointer is termed as a file pointer.

– The FILE structure is nothing but a stream of characters/bytes which acts as a


logical representative of the actual file.

– If the file could not be opened then fopen() returns a NULL.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 12
Version No: 2.0

12
High Level I/O functions (Contd…)

• Functions to close a File.


– fclose() is the counterpart of fopen() and its prototype is int fclose( FILE *stream );.

– The argument to fclose() is the FILE pointer returned by fopen().

– fclose() returns 0 if the file was closed successfully otherwise it returns -1.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 13
Version No: 2.0

•Program to demonstrate fopen() and fclose()


void main()
{
FILE *fp;
fp=fopen("Hello.C","r");
if(!fp)
printf("\n File cannot be opened");
else
{
/*Code to read data from the file*/
fclose(fp);
}
}

13
High Level I/O functions (Contd...)
• Functions for reading characters.
– fgetc()is a function to read characters from a file and its prototype is int fgetc( FILE
*stream );

– The argument to fgetc() is the FILE pointer returned by fopen().

– fgetc() returns the character read as an int or returns EOF to indicate an error or
end of file.

– EOF is a macro which is # defined to -1.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 14
Version No: 2.0

14
High Level I/O functions (Contd…)
• Functions for writing characters.
– fputc() is a function to write characters to a file and its prototype is int fputc( int c,
FILE *stream );

– The first argument to fputc() is the character to be written to the file.

– The second argument to fputc() is the FILE pointer returned by fopen().

– fputc() returns the character written to the file. It returns a EOF to indicate an error.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 15
Version No: 2.0

•Program to copy the contents of one file to another using fgetc() and fputc()
void main()
{
char ch; FILE *infile,*outfile;
infile=fopen("abc.txt","r");
if(!infile)
{
printf("\nInput File cannot be opened");
exit(1);
}
else
{
outfile=fopen("xyz.txt","w");
if(!outfile)
{
printf("\nOutput File cannot be opened");
fclose(infile);
exit(1);
}
else
{
while(1)
{
ch=fgetc(infile);
if(ch == EOF)
break;
else
fputc(ch,outfile);
}
fclose(infile); fclose(outfile);
printf("\nFile copy done!");
}
}
}

15
High Level I/O functions (Contd…)
• Functions for reading lines
– fgets()is a function to read lines from a file and its prototype is char *fgets( char
*string, int n, FILE *stream );

– The first argument to fgets() is a character pointer which points to a buffer which will
receive the line read from the file.

– The second argument to fgets() is the size of the buffer.

– The Third argument to fgets() is the FILE pointer returned by fopen().

– fgets() returns NULL to indicate an error or end of file.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 16
Version No: 2.0

16
High Level I/O functions (Contd…)
• Functions for writing lines
– fputs() is a function to write lines to a file and its prototype is int fputs( const char
*string, FILE *stream );

– The first argument to fputc() is a character pointer which points to a buffer which
holds the string to be written to the file.

– The second argument to fputc() is the FILE pointer returned by fopen().

– fputs() returns a non negative number if successful else It returns a EOF to indicate
an error.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 17
Version No: 2.0

•Program to copy the contents of one file to another using fgets() and fputs()
void main() {
char ch, buff[80]; FILE *infile,*outfile;
infile=fopen("abc.txt","r");
if(!infile)
{
printf("\nInput File cannot be opened");
exit(1); }
else
{
outfile=fopen("xyz.txt","w");
if(!outfile)
{
printf("\nOutput File cannot be opened");
fclose(infile);
exit(1); }
else
{
while(1)
{
ch=fgets(buff,80,infile);
if(ch == NULL)
break;
else
fputs(buff,outfile); }
fclose(infile); fclose(outfile);
printf("\nFile copy done!"); } } }

17
High Level I/O functions (Contd…)
• Functions for reading blocks of data
– fread()is a function to read blocks of data from a file and its prototype is size_t
fread( void *buffer, size_t size, size_t count, FILE *stream );

– A block will have records of the same type. Example of record could be employee
record which stores employee details like employee #, Name date of joining etc.

– fread returns the number of full items actually read, which may be less than count if
an error occurs or if the end of the file is encountered before reaching count.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 18
Version No: 2.0

18
High Level I/O functions (Contd…)
• Functions for reading blocks of data
– The first argument to fread() is a void pointer, which points to a buffer that receives
the blocks read from the file.

– The second argument to fread() is the size of each record.

– The third argument to fread() is the number of records to be read.

– The fourth argument to fread() is the FILE pointer returned by fopen().

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 19
Version No: 2.0

•Program to illustrate the usage of fread() to read blocks of data


struct employee {int eno; char name[20]; };
int main()
{
struct employee e[3];
FILE *infile;
int count,i;
infile=fopen("emp.dat","r");
if(infile == NULL)
{
printf("\nError in opening the input file");
exit(1);
}
else
{
count=fread(e,sizeof(struct employee),3,infile);
printf("\n%d out of 3 records were read sucessfully from the
file\n",count);
for(i=0;i<count;i++)
{
printf("\nEmployee Number : %d",e[i].eno);
printf("\tEmployee Name : %s",e[i].name);
fclose(infile);
}
}
return 0;
}

19
High Level I/O functions (Contd…)
• Functions for writing blocks of data
– fwrite()is a function to write blocks of data to a file and its prototype is size_t fwrite(
const void *buffer, size_t size, size_t count, FILE *stream );

– A block will have records of the same type. Example of record could be employee
record which stores employee details like employee #, Name date of joining etc.

– fwrite() returns the number of full items actually written, which may be less than
count if an error occurs.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 20
Version No: 2.0

20
High Level I/O functions (Contd…)
• Functions for writing blocks of data
– The first argument to fwrite() is a void pointer to a constant, which points to a buffer
that has the blocks of data, to be written to the file.

– The second argument to fwrite() is the size of each record.

– The third argument to fwrite() is the number of records to be written.

– The fourth argument to fwrite() is the FILE pointer returned by fopen().

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 21
Version No: 2.0

•Program to illustrate the usage of fwrite() to write blocks of data


struct employee { int eno; char name[20]; };
int main()
{
struct employee e[3];
e[0].eno=1;
strcpy(e[0].name,"Amit");
e[1].eno=2;
strcpy(e[1].name,"Raj");
e[2].eno=3;
strcpy(e[2].name,"Vishal");
FILE *outfile;
int count;
outfile=fopen("emp.dat","w");
if(outfile == NULL)
{
printf("\nError in opening the output file");
exit(1);
}
else
{
count=fwrite(e,sizeof(struct employee),3,outfile);
printf("\n%d out of 3 records were written sucessfully to the file\n",count);
fclose(outfile);
}
return 0;
}

21
High Level I/O functions (Contd…)
• High Level functions can be categorized as text mode and binary mode
functions and so far we have seen the text mode functions.

• There are 3 main areas where text and binary mode files are different
– Handling newlines.
– Representation of End of File.
– Storage of numbers.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 22
Version No: 2.0

22
High Level I/O functions (Contd...)
• Behavior of newlines if a file is opened in Binary mode.
– In a text mode operation every newline character is converted to a carriage return –
linefeed combination when it is written to the disk. Likewise the carriage return –
linefeed combination is converted to a newline character when it is read from the
disk.

– In a binary mode operation the above mentioned conversions don’t take place.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 23
Version No: 2.0

Text Mode file operation. Binary mode file operation.

void main() void main()


{ {
FILE *infile; FILE *infile;
int count=0; int count=0;
char ch; char ch;
infile=fopen("emp.dat","r"); infile=fopen("emp.dat","r");
if(infile == NULL) if(infile == NULL)
{ {
printf("\nError in opening the input file"); printf("\nError in opening the input file");
exit(1); exit(1);
} }
else else
{ {
while((ch=fgetc(infile))!=EOF) while((ch=fgetc(infile))!=EOF)
count++; count++;
fclose(infile); fclose(infile);
printf("\nNumber of characters read is printf("\nNumber of characters read is
%d",count); %d",count);
} }
} }

23
High Level I/O functions (Contd…)
• End of File detection for a file opened in Binary mode
– In a text mode operation, a special character, whose ASCII value 26, is inserted
after the last character in the file to mark the end of file.

– In a binary mode operation there is no special character to indicate end of file. The
binary mode files keep track of the end of file from the number of characters present
in the directory entry of the file.

– A file opened for writing in binary mode should be opened for reading in binary mode
only.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 24
Version No: 2.0

24
High Level I/O functions (Contd...)
• Storage of numbers for a file opened in binary mode
– In text mode operation, integers & floats are stored as strings of characters i.e.
12345 will occupy 5 bytes because individual digits are stored as characters
occupying one byte each.

– In a binary mode operation, integers and floats are stored exactly in the same way
as they are stored in memory i.e. integers will occupy 2 bytes and floats will occupy
4 bytes.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 25
Version No: 2.0

Text Mode file operation. Binary mode file operation.

void main() void main()


{ {
FILE *infile; FILE *infile;
int count=0; int count=0;
char ch; char ch;
infile=fopen("emp.dat","r"); infile=fopen("emp.dat","r");
if(infile == NULL) if(infile == NULL)
{ {
printf("\nError in opening the input file"); printf("\nError in opening the input file");
exit(1); exit(1);
} }
else else
{ {
while((ch=fgetc(infile))!=EOF) while((ch=fgetc(infile))!=EOF)
count++; count++;
fclose(infile); fclose(infile);
printf("\nNumber of characters read is printf("\nNumber of characters read is
%d",count); %d",count);
} }
} }

25
High Level I/O functions (Contd…)
• Functions for random access of file contents
– fseek() is a function to move the file pointer to a specified location and its prototype
is int fseek( FILE *stream, long offset, int origin );

– If successful, fseek() returns zero. Otherwise, it returns a nonzero value.

– The value of offset can be a negative value also.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 26
Version No: 2.0

26
High Level I/O functions (Contd...)
• Functions for random access of file contents
– The first argument to fseek() is the FILE pointer returned by fopen().

– The second argument specifies the number of offset bytes from the initial position.

– The third argument specifies the initial position which could be one of the following
• SEEK_CUR Current position of file pointer
• SEEK_END End of file
• SEEK_SET Beginning of file

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 27
Version No: 2.0

•Program to illustrate the usage of fseek()


The program below makes use of fseek() to jump to the 4th employee record in
the file.
struct employee{int eno;char name[20];};
int main()
{
struct employee e;
FILE *infile;
int count,i;
infile=fopen("emp.dat","r");
if(infile == NULL)
{
printf("\nError in opening the input file");
exit(1);
}
else
{
if(fseek(infile,3*sizeof(struct employee),SEEK_SET))
{
printf("\nError in seek operation");
exit(1);
}
count=fread(&e,sizeof(struct employee),1,infile);
printf("\nEmployee Number : %d",e.eno);
printf("\tEmployee Name : %s",e.name);
fclose(infile);
}
return 0;
} 27
High Level I/O functions (Contd…)
• Function for returning the current position of the file pointer.
– ftell() is a function to get the current position of a file pointer and its prototype is long
ftell( FILE *stream );

– The argument to ftell() is the FILE pointer returned by fopen().

– On error, ftell() returns –1L.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 28
Version No: 2.0

•Program to illustrate the usage of ftell() to determine the file size.


int main()
{
FILE *infile;
int count,i;
infile=fopen("emp.dat","r");
if(infile == NULL)
{
printf("\nError in opening the input file");
exit(1);
}
else
{
fseek(infile,0,SEEK_END);
printf("\nFile size is %d",ftell(infile));
}
return 0;
}

28
High Level I/O functions (Contd…)
• Function for detecting errors in read/write operations.
– ferror() is a function which reports any errors that might have occurred during
read/write operation on a file.

– It returns a zero if the read/write is successful and a nonzero value in case of a


failure.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 29
Version No: 2.0

29
High Level I/O functions (Contd…)
• Function for repositioning the file pointer to the beginning of a file.
– rewind() repositions the file pointer to the beginning of a file and its prototype is void
rewind( FILE *stream );

– The argument to rewind() is the FILE pointer returned by fopen().

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 30
Version No: 2.0

30
Command Line Arguments
• Just like any other function, we can pass arguments to main( ) .The function
main( ) can have two arguments traditionally named as argc & argv.

• Syntax:
– main (int argc, char *argv[]){ }

• argv is an array of pointers to strings. argc is an integer whose value is equal


to the no of strings to which argv points. argv[argc] is always NULL.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 31
Version No: 2.0

•Program to demonstrate command line arguments


int main(int argc, char *argv[])
{ FILE *outfile,*infile; char ch;
if(argc != 3)
{ printf("\n Incorrect No. of Arguments");
exit(1); }
infile=fopen(argv[1],"r");
if(infile == NULL)
{ printf("\nError in opening the file %s",argv[1]);
exit(1); }
else
{ outfile=fopen(argv[2],"w");
if(outfile == NULL)
{printf("\nError in opening the file %s",argv[1]);
exit(1); }
else
{ while((ch=fgetc(infile)) != EOF)
fputc(ch,infile);
printf("\n contents of %s is copied to
%s",argv[1],argv[2]);
}
}
return 0;
}

31
Summary
• Topics covered in this unit
– Concept of streams.

– High level File I/O functions.

– Command line arguments.

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 32
Version No: 2.0

32
Thank You!

Copyright © 2004, Infosys ER/CORP/CRS/LA07/003


Technologies Ltd 33
Version No: 2.0

33

Вам также может понравиться