×

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;
}

Related Topics

C/C++ Program to Find the Size of int, float, double and char

In this tutorial, we will learn how to use the sizeof operator to determine the size of each variable. Program to Determine Variable Size Write a C or C++ program to determine the...

2 minutes read.

Difference between Scope and Lifetime in C

In this article, we will discuss about the key differences between scope and lifetime in C, including their definitions, applications, and how they relate to one another. By the end...

8 minutes read.

Typecast vs. typedef in C

Typecast vs. typedef in C Typecast In the C programming language, converting the data type from one form to another is known as type casting or the type conversion. It is a...

5 minutes read.

Call Back Function in Embedded C

Callback function are one the most remarkable systems in C. A callback function is any code that is passed as a contention to another code, so this is the last...

3 minutes read.

Escape Sequence in C

An escape sequence is a sequence of character that used inside the string literal or character.  All the escape sequence is used with the backslash (\) symbol. The list of an...

1 minute read.

Multithreading in C interview questions

Q1. What exactly is a thread? Ans: A thread is a brief sequence of instructions intended to be planned and carried out by the CPU apart from the parent process. Q2. Can...

4 minutes read.

What is 2s Complement in C?

The complement of 2s in C is generated from the 1s in C. As we know, the 1s complement of a binary number is generated by converting bit 1 to...

4 minutes read.

Type qualifiers in C

Type qualifiers in C: In the C programming language, type qualifiers are the keywords that prepend to the variables to change their accessibility, i.e., we can tell that the type...

4 minutes read.

Results of Comparison Operations in C and C++

In this tutorial, we will explore comparison operators and how the system should compare an incoming value supplied as a context parameter to a given value or range of values. A...

2 minutes read.

C Function Argument and Return Values

Functions in the C programming language are declared to avoid repeatedly writing a performable block of code; it is the same in any programming language. When it comes to the...

3 minutes read.

What is the main in C?

In the C programming language, "main" is a predefined term or function. It is the primary function in every C program and is in charge of beginning and terminating the...

6 minutes read.

Segmentation Fault in C

Segmentation Fault in C In the C programming language, segmentation fault or segmentation violation or core dump is a condition that the hardware component raises to protect the memory by indicating...

4 minutes read.

How to lock top row in Excel

How to lock top row in excel While working with an Excel spreadsheet, the user utilizes the rows and columns to enter the details under various headings. Sometimes while scrolling the...

4 minutes read.

Conio.h in C

Header files are the source files with the extension of .h. In c language header files are referred to as the helping files and they contain definitions of various functions...

4 minutes read.

FIFO Example in the C Language

FIFO is an acronym that means "First In, First Out." It is a data structure handling method in which the first element is handled first, and the last element is...

3 minutes read.

memmove() in C

Introduction: In this article we are discuss about the memmove() function in C. This function transfers memory blocks from one location to another. The memmove() function is declared in the...

3 minutes read.

Branching Statements in C

What is branching in c? Branching gets its name from the fact that the computer can select which branch to follow.Programs written in the C language execute statements one after the...

6 minutes read.

Socket Programming in C

Socket programming is a process that connects the two or more nodes on a networking communication with respective to each other. One of the sockets that determines the socket (I.e.,...

5 minutes read.

Find median of 1D array using function in C

Introduction: Here, we discuss how we can find the median of a 1D array using a function in C. The median is the value in the middle of the sorted...

3 minutes read.

Big O Notation in C

Big O Notation in C: In the C programming language, we have so many algorithms and solutions to the problems that exist, which have different aspects and purposes to an...

3 minutes read.