There are many types of functions in C programming for handling file input/output (I/O). In this chapter you’ll learn how to handle C’s standard input/output using functions like fprintf(), fscanf(), fread(), fwrite(), fseek and more.
In C programming, a file is a place on your computer’s physical disk where data is stored.
Why is the file needed?
- All data is lost when the program terminates. But when saving to a file, the data is saved even after the program ends.
- If you have to enter a lot of data, it will take a long time to enter all the data. However, if you have a file containing all the data, you can easily access those contents with some C commands.
- You can transfer your data from one computer to another very easily.
C file type
When you deal with files, you will see two types of files that you need to know:
- Text file
- Binary file
Difference Between Text File and Binary Filetext file binary file Plain text file with .txt extension. are saved on your computer with the .bin extension. Saves data in text format (a,a,a,b), making editing much easier. Data is stored in binary format (0 and 1) instead of text, making editing difficult. Easily readable. Not readable. Can be maintained with less effort. Maintenance is very difficult. Occupies a lot of space in memory. Can hold a lot of information in less space. Provides poor security. Provides the highest level of security.
C file operations
There are four main operations for text or binary file operations in C programs:
- Create new file.
- Open existing file.
- Close the file.
- Reading data and adding data from existing files.
Working with C files
file
A pointer of type must be declared when you work with files . This declaration is required to establish communication between programs and files.
FILE *fptr;
Creating and editing C files
File opening is done through the fopen() library function under the “stdio.h” header file.
Syntax for opening C files
ptr = fopen("fileopen","mode")
For example:
fopen("E:\\cprogramming\\newFile.txt","w");
fopen("E:\\cprogramming\\oldFile.bin","rb");
- Assume that
E:\cprogramming
the first text file at location 1newFile.txt
does not already exist. The first functionnewFile.txt
creates a new file named according to file mode “w” .
The <W> mode of files allows you to create new files and edit/overwrite them. - Again assume the second binary file
oldFile.bin
file already exists in the E:\cprogramming location. The second function opens the existing file for reading in binary mode (‘rb’).
Opening a file in ‘r’ mode gives you only read permission, not change/write permission.
file mode | description | If the file does not exist |
---|---|---|
r | Opens the file for reading. | The fopen() function returns NULL if the file does not exist. |
rb | Opens the file for reading in binary mode. | The fopen() function returns NULL if the file does not exist. |
In | Opens the file for writing. | If the file exists, its contents will be overwritten. A new file will be created if the file does not exist. |
wb | Opens the file for writing in binary mode. | If the file exists, its contents will be overwritten. A new file will be created if the file does not exist. |
a | Opens the file to append data. So data can be appended to the end of the file. | A new file will be created if the file does not exist. |
ab | Opens file to append data in binary mode. So data can be appended to the end of the file. | A new file will be created if the file does not exist. |
r+ | Opens files for both reading and writing. | The fopen() function returns NULL if the file does not exist. |
rb+ | Opens files for both reading and writing in binary mode. | The fopen() function returns NULL if the file does not exist. |
in+ | Opens for both reading and writing. | If the file exists, its contents will be overwritten. A new file will be created if the file does not exist. |
wb+ | Opens files for both reading and writing in binary mode. | If the file exists, its contents will be overwritten. A new file will be created if it does not exist. |
a+ | Opens files for both reading and appending data. | A new file will be created if the file does not exist. |
ab+ | Opens files for both reading and appending data in binary mode. | A new file will be created if the file does not exist. |
Closing the C file
Both text and binary files should be closed after reading/writing.
File closing is done using the fclose() library function.
Syntax for closing C files
fclose(fptr); //Here fptr is the file pointer of the file to be closed
Reading and writing C text files
To read and write text files we use the fprintf()
and library functions respectively.fscanf()
fprintf()
and fscanf()
the function is two printf()
and scanf()
its file version. The only difference is that the fprint and fscanf functions expect at least one pointer to the two files.
Written in C Text file
Example: Writing to file using fprintf() function
#include
int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}
This program receives numbers from the user and program.txt
stores them in a file.
After compiling and running this program, you will see a file named program.txt in the C drive of your computer. When you open the file you will see the integer number you entered.
Reading from C Text file
Example: Reading file using fscanf() library function.
#include
int main()
{
int num;
FILE *fptr;
if ((fptr = fopen("C:\\program.txt","r")) == NULL){
printf("Error! opening file");
// If the file pointer returns NULL, the program will exit.
exit(1);
}
fscanf(fptr,"%d",&num);
printf("Value of n=%d",num);
fclose(fptr);
return 0;
}
This program program.txt
reads the integers present in the file and prints them on the screen.
If the file is successfully created in the first example then running this program will get the integer you entered.
Other functions like – fgetchar()
, fputc()
etc. can be used similarly.
Reading and writing to C binary files
fwrite()
The and fread()
library functions are used respectively to write binary files to and read binary files from your computer disk .
Working with C binary files
To write something to a binary file you need to use the fwrite() function. This function accepts four arguments. Namely, the address of the computer disk to record the data, the size of the data recorded on the disk, the number of data and the pointer to the file where the data will be stored.
Syntax for writing C binary files
fwrite(data_address, data_size, data_numbers, pointer_to_file);
Example: Writing binary file using fwrite().
#include
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","wb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
num.n1 = n;
num.n2 = 5n;
num.n3 = 5n + 1;
fwrite(&num, sizeof(struct threeNum), 1, *fptr);
}
fclose(fptr);
return 0;
}
With this program you program.bin
can create a new file named in C drive.
We have declared a structure variable with three numbers – n1, n2 and n3threeNum
and defined it as num in the main function.
Now we can store the value in the file using the fwrite() function inside the for loop.
The first parameter takes the address of the numthreeNum
variable and the second parameter takes the size of the structure.
Since we have inserted only one instance of num1
, the value of the third parameter is . The last parameter *fptr
points to the data store file.
Finally we close the file.
Reading from binary files
fwrite()
Like the function above fread()
, the function also accepts four arguments.
Syntax for reading binary files
fread(data_address, data_size, data_numbers, pointer_to_file);
Example: Reading data from binary file using fread() function:
#include
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");
// If the file pointer returns NULL, the program will exit.
exit(1);
}
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, *fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
With this program you program.bin
can read the same file and loop through the records of the file one after the other.
In simple terms, you can read a record of size into the num structure by the *fptr file pointer.threeNum
threeNum
Whatever you record in the example above will get the same record back.
Retrieving data via C fseek()
If there is a lot of information recorded in the file and it is necessary to access that record at a specific position, then the entire record needs to be looped.
This will waste a lot of memory and operation time. To overcome this problem you can use fseek() function which will save both time and effort.
The fseek() function easily moves the cursor to the desired record in the file.
Syntax of fseek()
fseek(FILE * stream, long int offset, int whence)
Here the first parameter of the function stream is the pointer to the file, the second parameter is the position of the record to find, and the third parameter is the location from which to start offset.
Whence | description |
---|---|
SACK_SET | Printing starts from the very beginning of the file (offset). |
SACK_END | Printing starts from the very end of the file (offset). |
SACK_CUR | Printing starts from the current location of the file cursor. |
Example: Application of fseek() function
#include
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");
// If the file pointer returns NULL, the program exits.
exit(1);
}
// The cursor goes to the end of the file at once.
fseek(fptr, sizeof(struct threeNum), SEEK_END);
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, *fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
This program starts reading records from the binary file in reverse direction (ie end to end) program.bin
and prints them immediately.