C-Programming Chapter 5 File-handling-C
C-Programming Chapter 5 File-handling-C
File Handling in C
1
Console oriented Input/Output
• Concept of files
Files
fp = fopen(“filename”, “mode”);
/*opens file with name filename , assigns identifier to fp */
• 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.
• 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:
fclose(f1);
} /*end main */
fscanf() and fprintf()
• similar to scanf() and printf()
• in addition provide file-pointer
• given the following
– file-pointer f1 (points to file opened in write mode)
– file-pointer f2 (points to file opened in read mode)
– integer variable i
– float variable f
• Example:
fprintf(f1, “%d %f\n”, i, f);
fprintf(stdout, “%f \n”, f); /*note: stdout refers to screen */
fscanf(f2, “%d %f”, &i, &f);
• fscanf returns EOF when end-of-file reached
getw() and putw()
fp = fopen(“input.dat”, “r”);
if (fp == NULL)
printf(“File could not be opened \n ”);
Random access to files
$ cc args.c -o args.out
$ ./args.out 2 join leave 6
6
leave
join
2
./args.out
$