MODULE 5 File Handling in C
MODULE 5 File Handling in 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()
The fscanf() function is used to read formatted data from the stream. The
syntax of fscanf() can be given as
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char name[80];
int roll_no;
fp = fopen("student.txt", "r");
if(fp==NULL)
{
printf("\n The file could not be opened");
exit(0);
}
printf("\n Enter the name and roll number of the student: ");
The function writes data that is formatted as specified by the format argument to the
specified stream. After the format parameter, the function can have as many
additional arguments as specified in the format.
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp;
int i;
char name[20];
float salary;
fp = fopen("student.txt", "w");
if (fp==NULL)
{
printf("\n The file could not be opened");
exit(1);
}
puts("\n Enter your name: ");
gets(name);
fflush(stdin);
puts("\n Enter your salary: ");
scanf("%f", &salary);
fclose(fp);
}
OUTPUT
Errors that occur during I/O
fp = fopen(“input.dat”, “r”);
if (fp == NULL)
printf(“File could not be opened \n ”);