File handling in C enables us to create, update, read, and delete the files stored on the local file system through our C program.
The following operations can be performed on a file.
- Creation of a new file (fopen with attributes as “a” or “a+” or “w” or “w++”)
- Opening an existing file (fopen)
- Reading from file (fscanf or fgets)
- Writing to a file (fprintf or fputs)
- Moving to a specific location in a file (fseek, rewind)
- Closing a file (fclose)
1). Opening File: fopen()
We must open a file before it can be read, write, or update. The fopen() function is used to open a file. The syntax of the fopen() is given below.
Syntax:-
FILE *fopen( const char * filename, const char * mode );
The fopen() function accepts two parameters:
- The file name (string). If the file is stored at some specific location, then we must mention the path at which the file is stored. For example, a file name can be like "c://some_folder/some_file.ext".
- The mode in which the file is to be opened. It is a string.
We can use one of the following modes in the fopen() function.
2). Closing a File: fclose()
The fclose() function returns zero on success, or EOF if there is an error in closing the file. This function actually flushes any data still pending in the buffer to the file, closes the file, and releases any memory used for the file. The EOF is a constant defined in the header file stdio.h.
Syntax:-
int fclose( FILE *fp );
3).Reading File : fscanf()
The fscanf() function is used to read set of characters from file. It reads a word from the file and returns EOF at the end of file.
Syntax:
int fscanf(FILE *stream, const char *format [, argument, ...])
Example:-
#include <stdio.h>
main(){
FILE *fp;
char buff[25]; //creating char array to store data of file
fp = fopen("file abc.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
}
Output:
Hello,scanf is use...
4). Writing File : fprintf()
The fprintf() function is used to write set of characters into file. It sends formatted output to a stream.
Syntax:
int fprintf(FILE *stream, const char *format [, argument, ...])
Example:-
#include <stdio.h>
main(){
FILE *fp;
fp = fopen("file.txt", "w"); //opening file
fprintf(fp, "Hello file by fprintf...\n"); //writing data into file
fclose(fp);//closing file
}
5). Writing a File: fputc()
6). Reading a File:fgetc()


0 Comments