Unit5 C Programming LA07
-
Upload
vikash-sharma -
Category
Documents
-
view
231 -
download
0
Transcript of Unit5 C Programming LA07
-
8/8/2019 Unit5 C Programming LA07
1/33
1
C Programming
File I/O in C
-
8/8/2019 Unit5 C Programming LA07
2/33
2
2ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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
-
8/8/2019 Unit5 C Programming LA07
3/33
3
3ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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.
-
8/8/2019 Unit5 C Programming LA07
4/33
4
4ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
Need for File I/O
The C Language has no provision for file I/O. The developers of a C compilerswrite 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/Ofunctions provided by the underlying operating system.
These functions in the I/O library are not a part of Cs formal definition but theyhave become a standard feature of C Language.
-
8/8/2019 Unit5 C Programming LA07
5/33
5
5ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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
File I/O in C
The treatment of files in C is very simple, unlike other programminglanguages 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 thoseprovided 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 buffermanagement has to be done by the programmer.
Text I/O functions open files in text mode whereas binary I/O functions openfiles in binary mode.
-
8/8/2019 Unit5 C Programming LA07
6/33
6
6ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 otherI/O devises.
-
8/8/2019 Unit5 C Programming LA07
7/33
7
7ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
Understanding Streams (Contd)
Illustrating a stream
C Program
Input Stream
Disk File
Output Stream
Understanding Streams
If a C Program has to write some data to a disk file, a output streamcorresponding 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 diskfile. 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 readfrom the disk file to the input stream by the operating system and the Cprogram 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 akeyboard.
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 whichcould be a serial port.
-
8/8/2019 Unit5 C Programming LA07
8/33
8
8ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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.
-
8/8/2019 Unit5 C Programming LA07
9/33
9
9ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
File Opening Modes
Searches file. If the file exists, loads it into memory and sets up a pointer whichpoints to the first character in it. If the file doesnt 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.
a
Searches file. If the file exists, contents are overwritten. If the file doesnt existsa new file is created. Returns a null if unable to open the file.
Operations possible - writing to the file.
w
Searches file. If the file exists, loads it into memory and sets up a pointer whichpoints to the first character in it. If the file doesnt exists it returns a null.
Operations possible - reading from the files
r
DescriptionMode
-
8/8/2019 Unit5 C Programming LA07
10/33
10
10ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
File Opening Modes (Contd...)
Same as a
Operations possible reading existing contents, appending new contents tothe end of file, cannot modify existing contents of the file.
a
Same as w
Operations possible writing new contents, reading them back and modifyingexisting contents of the file.
w
Same as r
Operations possible reading existing contents, writing new contents,modifying existing contents of the file.
r
DescriptionMode
-
8/8/2019 Unit5 C Programming LA07
11/33
11
11ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 themode in which the file has to be opened.
-
8/8/2019 Unit5 C Programming LA07
12/33
12
12ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 typeFILE 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 alogical representative of the actual file.
If the file could not be opened then fopen() returns a NULL.
-
8/8/2019 Unit5 C Programming LA07
13/33
13
13ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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.
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);
}
}
-
8/8/2019 Unit5 C Programming LA07
14/33
14
14ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 orend of file.
EOF is a macro which is # defined to -1.
-
8/8/2019 Unit5 C Programming LA07
15/33
15
15ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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.
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!");
}
}
}
-
8/8/2019 Unit5 C Programming LA07
16/33
16
16ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 willreceive 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.
-
8/8/2019 Unit5 C Programming LA07
17/33
17
17ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 whichholds 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 indicatean error.
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!"); } } }
-
8/8/2019 Unit5 C Programming LA07
18/33
18
18ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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_tfread( void *buffer, size_t size, size_t count, FILE *stream);
A block will have records of the same type. Example of record could be employeerecord 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 countifan error occurs or if the end of the file is encountered before reaching count.
-
8/8/2019 Unit5 C Programming LA07
19/33
19
19ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 receivesthe 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().
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
-
8/8/2019 Unit5 C Programming LA07
20/33
20
20ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 employeerecord which stores employee details like employee #, Name date of joining etc.
fwrite() returns the number of full items actually written, which may be less thancountif an error occurs.
-
8/8/2019 Unit5 C Programming LA07
21/33
21
21ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 bufferthat 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().
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;
}
-
8/8/2019 Unit5 C Programming LA07
22/33
22
22ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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.
-
8/8/2019 Unit5 C Programming LA07
23/33
23
23ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 thedisk.
In a binary mode operation the above mentioned conversions dont take place.
void main()
{
FILE *infile;
int count=0;
char ch;
infile=fopen("emp.dat","r");
if(infile == NULL)
{
printf("\nError in opening the input file");
exit(1);
}
else
{
while((ch=fgetc(infile))!=EOF)
count++;
fclose(infile);
printf("\nNumber of characters read is%d",count);
}
}
void main()
{
FILE *infile;
int count=0;
char ch;
infile=fopen("emp.dat","r");
if(infile == NULL)
{
printf("\nError in opening the input file");
exit(1);
}
else
{
while((ch=fgetc(infile))!=EOF)
count++;
fclose(infile);
printf("\nNumber of characters read is%d",count);
}
}
Binary mode file operation.Text Mode file operation.
-
8/8/2019 Unit5 C Programming LA07
24/33
24
24ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 insertedafter 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. Thebinary mode files keep track of the end of file from the number of characters presentin the directory entry of the file.
A file opened for writing in binary mode should be opened for reading in binary modeonly.
-
8/8/2019 Unit5 C Programming LA07
25/33
25
25ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 charactersoccupying one byte each.
In a binary mode operation, integers and floats are stored exactly in the same wayas they are stored in memory i.e. integers will occupy 2 bytes and floats will occupy4 bytes.
void main()
{
FILE *infile;
int count=0;
char ch;
infile=fopen("emp.dat","r");
if(infile == NULL)
{
printf("\nError in opening the input file");
exit(1);
}
else
{
while((ch=fgetc(infile))!=EOF)
count++;
fclose(infile);
printf("\nNumber of characters read is%d",count);
}
}
void main()
{
FILE *infile;
int count=0;
char ch;
infile=fopen("emp.dat","r");
if(infile == NULL)
{
printf("\nError in opening the input file");
exit(1);
}
else
{
while((ch=fgetc(infile))!=EOF)
count++;
fclose(infile);
printf("\nNumber of characters read is%d",count);
}
}
Binary mode file operation.Text Mode file operation.
-
8/8/2019 Unit5 C Programming LA07
26/33
26
26ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 prototypeis int fseek( FILE *stream, long offset, int origin);
If successful, fseek() returns zero. Otherwise, it returns a nonzero value.
The value of offsetcan be a negative value also.
-
8/8/2019 Unit5 C Programming LA07
27/33
27
27ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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
Program to illustrate the usage of fseek()
The program below makes use of fseek() to jump to the 4th employee record inthe 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;
}
-
8/8/2019 Unit5 C Programming LA07
28/33
28
28ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 longftell( FILE *stream);
The argument to ftell() is the FILE pointer returned by fopen().
On error, ftell() returns 1L.
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;
}
-
8/8/2019 Unit5 C Programming LA07
29/33
29
29ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 duringread/write operation on a file.
It returns a zero if the read/write is successful and a nonzero value in case of afailure.
-
8/8/2019 Unit5 C Programming LA07
30/33
30
30ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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 voidrewind( FILE *stream);
The argument to rewind() is the FILE pointer returned by fopen().
-
8/8/2019 Unit5 C Programming LA07
31/33
31
31ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
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.
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;
}
-
8/8/2019 Unit5 C Programming LA07
32/33
32
32ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
Summary
Topics covered in this unit
Concept of streams.
High level File I/O functions.
Command line arguments.
-
8/8/2019 Unit5 C Programming LA07
33/33
33ER/CORP/CRS/LA07/003
Version No: 2.0
Copyright 2004, InfosysTechnologies Ltd
Thank You!