File Handling Example
File Handling Example
#include <stdio.h>
#include <stdlib.h>
int main()
{
// file pointer variable to store the value returned by
// fopen
FILE* fptr;
// opening the file in read mode
fptr = fopen("filename.txt", "r");
// checking if the file is opened successfully
if (fptr == NULL) {
printf("The file is not opened. The program will "
"now exit.");
exit(0);
}
return 0;
}
Output
The file is not opened. The program will now exit.
CREATE A FILE IN C
The fopen() function can not only open a file but also can create a
file if it does not exist already. For that, we have to use the modes
that allow the creation of a file if not found such as w, w+, wb,
wb+, a, a+, ab, and ab+.
FILE *fptr;
fptr = fopen("filename.txt", "w");
// C Program to create a file
#include <stdio.h>
#include <stdlib.h>
int main()
{
// file pointer
FILE* fptr;
// creating file using fopen() access mode "w"
fptr = fopen("file.txt", "w");
// checking if the file is created
if (fptr == NULL) {
printf("The file is not opened. The program will "
"exit now");
exit(0);
}
else {
printf("The file is created Successfully.");
}
return 0;
}
Output
The file is created Successfully.
Function Description
fscanf() Use formatted string and variable arguments list
to take input from a file.
fgets() Input the whole line from the file.
fgetc() Reads a single character from the file.
fgetw() Reads a number from a file.
fread() Reads the specified bytes of data from a binary
file.
So, it depends on you if you want to read the file line by line or
character by character.
Example:
FILE * fptr;
fptr = fopen(“fileName.txt”, “r”);
fscanf(fptr, "%s %s %s %d", str1, str2, str3, &year);
char c = fgetc(fptr);
WRITE TO A FILE
The file write operations can be performed by the functions
fprintf() and fputs() with similarities to read operations. C
programming also provides some other functions that can be
used to write data to a file such as:
Function Description
fprintf() Similar to printf(), this function use formatted
string and varible arguments list to print output to
the file.
fputs() Prints the whole line in the file and a newline at
the end.
fputc() Prints a single character into the file.
fputw() Prints a number to the file.
fwrite() This functions write the specified amount of bytes
to the binary file.
Example:
FILE *fptr ;
fptr = fopen(“fileName.txt”, “w”);
fprintf(fptr, "%s %s %s %d", "We", "are", "in", 2012);
fputc("a", fptr);
Closing a File
The fclose() function is used to close the file. After successful file
operations, you must always close a file to remove it from the
memory.
Syntax of fclose()
fclose(file_pointer);
where the file_pointer is the pointer to the opened file.
Example:
FILE *fptr ;
fptr= fopen(“fileName.txt”, “w”);
---------- Some file Operations -------
fclose(fptr);
This program reads the text from the file named GfgTest.c
which we created in the previous example and prints it in the
console