File Handling
File Handling
1
Storage seen so far
All variables stored in memory
Problem: the contents of memory are wiped out
when the computer is powered off
Example: Consider keeping students’ records
100 students records are added in array of
structures
Machine is then powered off after sometime
When the machine is powered on, the 100 records
entered earlier are all gone!
Have to enter again if they are needed
2
Solution: Files
A named collection of data, stored in secondary
storage like disk, CD-ROM, USB drives etc.
Persistent storage, not lost when machine is
powered off
Save data in memory to files if needed (file
write)
Read data from file later whenever needed (file
read)
3
Organization of a file
Stored as sequence of bytes, logically contiguous
May not be physically contiguous on disk, but you
do not need to worry about that
The last byte of a file contains the end-of-file
character (EOF), with ASCII code 1A (hex).
While reading a text file, the EOF character can be
checked to know the end
Two kinds of files:
Text : contains ASCII codes only
Binary : can contain non-ASCII characters
Example: Image, audio, video, executable, etc.
5
Opening a File
A file must be “opened” before it can be used.
FILE *fp;
:
fp = fopen (filename, mode);
fp is declared as a pointer to the data type FILE.
filename is a string - specifies the name of the file.
fopen returns a pointer to the file which is used in all
subsequent file operations.
mode is a string which specifies the purpose of opening
the file:
“r” :: open the file for reading only
“w” :: open the file for writing only
“a” :: open the file for appending data to it
Opening a File: fopen()
7
Example: opening file.dat for write
FILE *fptr;
char filename[ ]= "file2.dat";
fptr = fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE CREATION”);
/* DO SOMETHING */
}
8
Modes for opening files
The second argument of fopen is the mode in
which we open the file.
"r" : opens a file for reading (can only read)
Error if the file does not already exists
"r+" : allows write also
9
Modes for opening files
The second argument of fopen is the mode in
which we open the file.
"r" : opens a file for reading (can only read)
Error if the file does not already exists
"r+" : allows write also
10
Modes for opening files
The second argument of fopen is the mode in
which we open the file.
"r" : opens a file for reading (can only read)
Error if the file does not already exists
"r+" : allows write also
12
Usage of exit( )
FILE *fptr;
char filename[]= "file2.dat";
fptr = fopen (filename,"w");
if (fptr == NULL) {
printf (“ERROR IN FILE CREATION”);
/* Do something */
exit(-1);
}
………rest of the program………
13
Writing to a file: fprintf( )
fprintf() works exactly like printf(), except that
its first argument is a file pointer. The
remaining two arguments are the same as
printf
The behaviour is exactly the same, except that
the writing is done on the file instead of the
display
FILE *fptr;
fptr = fopen ("file.dat","w");
fprintf (fptr, "Hello World!\n");
fprintf (fptr, “%d %d”, a, b);
14
Reading from a file: fscanf( )
fscanf() works like scanf(), except that its first
argument is a file pointer. The remaining two
arguments are the same as scanf
The behaviour is exactly the same, except
The reading is done from the file instead of from
the keyboard (think as if you typed the same thing
in the file as you would in the keyboard for a scanf
with the same arguments)
The end-of-file for a text file is checked differently
(check against special character EOF)
15
Reading from a file: fscanf( )
FILE *fptr;
EOF checking in a loop
fptr = fopen (“input.dat”, “r”);
/* Check it's open */ char ch;
if (fptr == NULL) while (fscanf(fptr, “%c”,
{ &ch) != EOF)
printf(“Error in opening file \n”); {
exit(-1); /* not end of file; read */
}
}
fscanf (fptr, “%d %d”,&x, &y);
16
Reading lines from a file: fgets()
Takes three parameters
a character array str, maximum number of characters
to read size, and a file pointer fp
Reads from the file fp into the array str until any
one of these happens
No. of characters read = size - 1
\n is read (the char \n is added to str)
EOF is reached or an error occurs
‘\0’ added at end of str if no error
Returns NULL on error or EOF, otherwise returns
pointer to str
17
Reading lines from a file: fgets()
FILE *fptr;
char line[1000];
/* Open file and check it is open */
while (fgets(line,1000,fptr) != NULL)
{
printf ("Read line %s\n",line);
}
18
Writing lines to a file: fputs()
Takes two parameters
A string str (null terminated) and a file pointer
fp
Writes the string pointed to by str into the
file
Returns non-negative integer on success,
EOF on error
19
Reading/Writing a character:
fgetc(), fputc()
Equivalent of getchar(), putchar() for
reading/writing char from/to keyboard
Exactly same, except that the first
parameter is a file pointer
Equivalent to reading/writing a byte (the
char)
int fgetc(FILE *fp);
int fputc(int c, FILE *fp);
Example:
char c;
c = fgetc(fp1); fputc(c, fp2); 20
Formatted and Un-formatted I/O
Formatted I/O
Using fprintf/fscanf
Can specify format strings to directly read as
integers, float etc.
Unformatted I/O
Using fgets/fputs/fgetc/fputc
No format string to read different data types
Need to read as characters and convert explicitly
21
Files and Streams
Read/Write functions in standard library
getc
Reads one character from a file
Takes a FILE pointer as an argument
putc
Writes one character to a file
Takes a FILE pointer and a character to write as
an argument
fputc( 'a', stdout ) equivalent to
putchar( 'a’ )
fscanf / fprintf
File processing equivalents of scanf and
printf
Read/Write Operations on Files
The simplest file input-output (I/O) function are getc and putc.
getc is used to read a character from a file and return it.
char ch; FILE *fp;
…..
ch = getc (fp) ;
getc will return an end-of-file marker EOF, when the end of the
file has been reached.
putc is used to write a character to a file.
char ch; FILE *fp;
……
putc (ch, fp) ;
Closing a file
Should close a file when no more read/write
to a file is needed in the rest of the program
File is closed using fclose() and the file
pointer
FILE *fptr;
char filename[]= "myfile.dat";
fptr = fopen (filename,"w");
fprintf (fptr,"Hello World of filing!\n");
…. Any more read/write to myfile.dat….
fclose (fptr);
24
Examples
FILE *in, *out ;
in = fopen (“mydata.dat”, “r”) ;
out = fopen (“result.dat”, “w”);
FILE *empl ;
char filename[25];
scanf (“%s”, filename);
empl = fopen (filename, “r”) ;
Closing a File
After all operations on a file have been completed, it
must be closed.
Ensures that all file data stored in memory buffers are
properly written to the file.
General format: fclose (file_pointer) ;
FILE *xyz ;
xyz = fopen (“test.txt”, “w”) ;
…….
fclose (xyz) ;
Contd
fclose( FILE pointer )
Closes specified file
Performed automatically when program ends
main() {
FILE *in, *out ;
char c ;
#include <stdio.h>
int main()
{ FILE *fileA, /* first input file */
*fileB, /* second input file */
*fileC; /* output file to be created */
int num1, /* number to be read from first file */
num2; /* number to be read from second file */
int f1, f2;
36
What are they?
A program can be executed by directly
typing a command with parameters at the
prompt
$ cc –o test test.c
$ ./a.out in.dat out.dat
$ prog_name param_1 param_2 param_3
..
The individual items specified are
separated from one another by spaces
First item is the program name
37
What do they mean?
Recall that main() is also a function
It can also take parameters, just like other
C function
The items in the command line are passed
as parameters to main
Parameters argc and argv in main keeps
track of the items specified in the
command line
38
How to access them?
int main (int argc, char *argv[]);
argc=3
./a.out
s.dat
d.dat
argv
40
Contd.
Still there is a problem
All the arguments are passed as strings in argv[ ]
But the intention may have been to pass an
int/float etc.
Solution: Use sscanf()
Exactly same as scanf, just reads from a string
(char *) instead of from the keyboard
The first parameter is the string pointer, the next
two parameters are exactly the same as scanf
41
Example
Write a program that takes as command line
arguments 2 integers, and prints their sum