File Operations in C
Why do I need the file?
All data will be lost when the program exits. Saving data to a file keeps it safe even if the program stops working. If there are many input items, it will take time to input them. On the other hand, if you have a file with all your data, you can access it quickly and easily with a few C commands. It also allows you to quickly and easily transfer data from one computer to another without making any changes.
File Types
There are two file typesyou should be aware of while working.Binary and Text Files Text files are regular .txt files. You caneasily create text files using a simple text editor like Notepad.By opening these files, you can read the entire contents of these files in plain text. Content can be easily edited or deleted.
They take up more storage space, offer minimal security, require minimal maintenance, and are easy to read 2 most binaries on your computer are .bin file store data in binary format (0s and 1s) instead of plain text. While they can contain higher levels of information, they are effectively meaningless and offer priority security over text records.
The operations performed on files are:
- Creation of a new file (fopen)
- 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)
Buffer Memory:
Files must be loaded from the disk into buffers before they can be read or written. A file is automatically opened when it is opened in read or write mode. Why do we need buffer space between the program and the diskto read, write, or perform other operations on the file? The question arises whether. This is because every time a character is written to or read from the disk, the process of accessing the disk becomes inefficient.
Every time a file is accessed, the system has to adjust the read/write head correctly, which takes time, so it uses a buffer memory that copies the file from the physical disk and performs all read and write operations on the copy of the file in a buffer. Changes made to the file are reflected in the disk-based file when the file is closed.
Not copying a fileto a buffer and using physical memorypreventsmultiple concurrent read and write operations on the same file.In this scenario, other users' data may change dynamically, leading to data inconsistencies and hijacking.
Creation of a New File
The file modes play a crucial role when creating or opening a file. We use the file mode "w" to create a new file. For creating a new file, the syntax is as follows:
FILE *fp;
fp=fopen("NewDoc.txt","w");
Opening an Existing File
Using the function fopen(), we must open a file before reading or writing to it. We can read the file's contents by opening it in read mode, also known as "r." The file is first loaded into the buffer and searched for on the disk when the file is opened in "read mode." The first character in the buffer will be pointed to by setting a char pointer. To open a file in "read mode," the syntax is:
FILE *fp; fp=fopen("Doc.txt","r");
- "r": file search If the file was successfully opened, fopen loads it into memory and sets the pointer to the first character Fopen( ) returns NULL if the file cannot be opened.
- "rb" means open for reading in binary mode. fopen( ) Returns NULL if the does not exist.
- "w" - search document. If the file exists, the contents of the file will be overwritten. A new file will be created if the first file is not found. NULL is returned if the file cannot be opened.
- "wb" isopenfor writing in binary mode. If the file exists, the contents of the filewill be overwritten. If the file does not exist, it will be created.
- "a": file search If the file was successfully opened, fopen loads it into memory and creates a pointer to the last character.A new file will be created if the first file is not found. NULL is returned if the file cannot be opened.
- "ab": Binary mode open for appending. The file is complete with data. If the file does not exist, it will be created.
- "r+": file search If opened successfully, fopen( loads it into memory and creates a pointer to the first character NULL is returned ifthe file cannot be opened.
- "rb+": Binary mode open for reading and writing fopen( ) Returns NULL if the file does not exist.
- "w+": File search If the file exists, the contents of the file will be overwritten. A new file is created when the previous file is deleted. NULL is returned if the file cannot be opened.
- "wb+" - Binary mode open for reading and writing. If the file exists, the contents of the file will be overwritten. If the file does not exist, it will be created.
- "a+" - file search. If the file was opened successfully, fopen(loads it into memory and sets a pointer to the last character. If the first character is not found, a new file is created. This returns NULL if it cannot.
- "ab+" – Binary mode is open for both reading and appending. If the file does not exist, it will be created.
Reading a File
Each time the file is opened, a pointer variable pointing to the first character is passed to thefile.The example above opened the file in "read mode". We use an additional function, fgetc(), to read the file's contents. This function moves the pointer to the next character and fetches or reads the first character from the current position.
Characters in the file are read this way individually. A while loop that runs indefinitely uses the fgetc() function. However, looping indefinitely is impractical, so the EOF or End of File macros was defined in the stdio.h header file. The functions fscanf and fgets can carry out the file read operations. The file pointer was added as a parameter to both functions, which carried out the same operations as scanf and gets.
Therefore, it is up to you to decide whether to read the file character by character or line by line. After reading all the characters in the file, the fgetc() function returns the EOF macro. Another function does the same thing as fgetc(): getc(). The syntax for reading a file using the fgetc() function is:
while(1) {
ch=fgetc(FP);
if(ch==EOF)
break;
//print ch }
Writing to a File
We need to open a file in the write mode or "w" mode before we can write to it. We use the function fputc() to write to the file now that we have opened it in write mode. A while loop can be used to write to the file, ending when all the characters have been written. The following is how to use the fputc() function:
FILE *fw;
fw=fopen("Doc1.txt","w");
char ch = 'a';
fputc(ch,fw);
Closing a File
It is essential to close the file after we have finished reading, writing, or performing other file operations. The file is closed with the help of the function fclose(). The file is closed using the same file pointer, not the file name.
fclose(fp);
fclose(fw);
Program to Open a File, Write in it, and Close the File
// C program to Open a File,
// Write in it, And Close the File
# include <stdio.h>
# include <string.h>
int main( )
{
// Declare the file pointer
FILE *filePointer ;
// Get the data to be written in file
char dataToBeWritten[50]
= "GeeksforGeeks-A Computer Science Portal for Geeks";
// Open the existing file GfgTest.c using fopen()
// in write mode using "w" attribute
filePointer = fopen("GfgTest.c", "w") ;
// Check if this filePointer is null
// which maybe if the file does not exist
if ( filePointer == NULL )
{
printf( "GfgTest.c file failed to open." ) ;
}
else {
printf("The file is now opened.\n") ;
// Write the dataToBeWritten into the file
if ( strlen ( dataToBeWritten ) > 0 ) {
// writing in the file using fputs()
fputs(dataToBeWritten, filePointer) ;
fputs("\n", filePointer) ;
}
// Closing the file using fclose()
fclose(filePointer) ;
printf("Data successfully written in file GfgTest.c\n");
printf("The file is now closed.") ;
}
return 0;
}
Program to Read from a binary file using fread()
#include <stdio.h>
#include <stdlib.h>
struct threeNum
{
int n1, n2, n3;
};
int main()
{
int n;
struct threeNumnum;
FILE *fptr;
if ((fptr = fopen("C:\\program.bin","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n) //Program Code Submitted by SusobhanAkhuli
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d", num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}