File Handling
File Handling
Real-life applications
Large data volumes
E.g. physical experiments (CERN collider), human
genome, population records etc.
Need for flexible approach to store/retrieve data
Concept of files
Files
File place on disc where group of related data is
stored
E.g. your C programs, executables
Naming
Opening
Reading
Writing
Closing
Filename
String of characters that make up a valid filename
for OS
fp
contains all information about file
Communication link between system and program
Mode can be
r open file for reading only
w open file for writing only
a open file for appending (adding) data
Different modes
Writing mode
if file already exists then contents are deleted,
else new file with specified name created
Appending mode
if file already exists then file opened with contents safe
else new file created
Reading mode
if file already exists then opened with contents safe
else error occurs.
FILE *p1, *p2;
p1 = fopen(data,r);
p2= fopen(results,
w);
Additional modes
r+ open to beginning for both reading/writing
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
If want to change mode of file, then first close and open again
Closing a file
Syntax:
fclose(file_pointer);
Example:
FILE *p1, *p2;
p1 = fopen(INPUT.txt, r);
p2 =fopen(OUTPUT.txt, w);
..
..
fclose(p1);
fclose(p2);
syntax: c = getc(fp2);
c : a character variable
fp2 : pointer to file opened with mode r
while((c=getchar()) != EOF)
/*get char from keyboard until
CTL-Z*/
putc(c,f1);
/*write a character to INPUT */
fclose(f1);
/* close INPUT */
f1=fopen(INPUT, r);
/* reopen file */
while((c=getc(f1))!=EOF)
INPUT*/
printf(%c, c);
fclose(f1);
} /*end main */
syntax: i = getw(fp2);
i : an integer variable
fp2 : pointer to file opened with mode r
#include <stdio.h>
main()
{ int i, sum2=0;
FILE *f2;
/* open files */
f2 = fopen("int_data.txt","w");
/* write integers to files in
binary and text format*/
for(i=10;i<15;i++)
printf(f2,"%d\n",i);
fclose(f2);
f2 = fopen("int_data.txt","r");
while(fscanf(f2,"%d",&i)!=EOF)
{ sum2+=i; printf("text file: i=
%d\n",i);
} /*end while fscanf*/
printf("text sum=%d\n",sum2);
fclose(f2);
}
$ ./a.out
text file: i=10
text file: i=11
text file: i=12
text file: i=13
text file: i=14
text sum=60
$ more int_data.bin
^@^@^@^K^@^@^@^L^
@^@^@^M^@^@^@^N
^@^@^@
$
Error handling
given file-pointer, check if EOF reached, errors
while handling file, problems opening file etc.
check if EOF reached: feof()
feof() takes file-pointer as input, returns nonzero
if all data read and zero otherwise
if(feof(fp))
printf(End of data\n);
Example args.c
#include <stdio.h>
main(int argc,char *argv[])
{
while(argc>0)
/* print out all arguments in reverse order*/
{
printf("%s\n",argv[argc-1]);
argc--;
}
}
$ cc args.c -o args.out
$ ./args.out 2 join leave 6
6
leave
join
2
./args.out
$