C Tutorial

C Tutorial C Language Environment Setup Execution flow of C program C printf and Scanf C Data type C Token Variable in C Operators in C Comments in C Escape Sequence in C C – Storage Classes C Decision control statement Loop Statement in C Break, continue and goto statement in C Type Casting in C Function in C Recursion in C String in C C Array Pointer in C Dynamic memory allocation C –Structure Nested Structure in C Union in C File Handling in C C pre-processor Static Function In C Sizeof In C Selection Sort In C Scope Of Variables In C Runtime Vs Compile Time In C Random Access Lseek In C Queue Implementation In C Pseudo Code In C Prototype In C Pointer To Pointer In C Pointer Arithmetic In C Passing Array To Function In C Null Character In C Merge Sort In C Macros In C Library Functions In C Memory Leak In C Int In C Goto And Labels In C Fibonacci Series In C Fflush In C Derived Data Types In C Data Types In C Const Vs Volatile In C Character Set In C Character Class Tests In C Calloc In C C Pointers Arrays In C Include In C Clrscr In C C Vs Java String Literals In C Types Of Pointers In C Variables In C Volatile In C Why C Is A Middle Level Language Infix To Postfix Program In C Ceil function in C LCM of two numbers in C Quick sort in C Static in C function pointer as argument in C Top Array Keywords in C Add two numbers using the function in C Armstrong program in C using function Array, Declaring Arrays and Array Initialization Limitations of Inline Function in C Merge and Merge sort with example in C Do-While Loop in C For Loop in C While-Loop in C Difference between while and do-while loop in C Array Of Structures in C Data Structures And Algorithms in C Types Of Structures In C How to Avoid Structure Padding in C Use of Structure in C Do WHILE LOOP in C Programming Examples For Loop in C Programming Examples Entry Control Loop in C Exit control loop in C Infinite loop in C Nested loop in C pow() function in C String Handling functions in C Prime Number code in C Factorial Program in C using For Loop Factorial Program in C Using While Loop Fibonacci Series in C Using For Loop Fibonacci series in C using while loop Prime Number Program in C using for Loop While Loop in C programming examples Built-in functions in C Assert() Function C vs Java Strings Call Back Function in Embedded C Else If Ladder fgets() function Ftell() Function getc() function getch() function gets() function Heap Sort Nested if-else statement Pi() Function Positioning of file Write() function abs() function in C Attributes in C C program to find factorial of a number using Recursion Ferror() in c fopen() function in C Fibonacci series program in C using Recursion Formatted Input and output function in C Snake Game in C User Defined Functions in C Beep() function in C Cbrt() function in C Hook() function in C Isalnum() function in C C Program to find the Roots of a Quadratic Equation C Switch Statements Difference between rand() and srand() function in C Difference between while and for loop in C Doubly Linked list in C Example of Iteration in C How to use atoi() function in C How to use floor() function in C How to use sine() function in C How to use Typedef Struct in C Integer Promotions in C C Program Swap Numbers in cyclic order Using Call by Reference C Program to Find Largest Number Using Dynamic Memory Allocation C Program to Find the Largest Number using Ternary Operator C/C++ Program to Find the Size of int, float, double and char Find the Largest Three Distinct Elements in an Array using C/C++ Loop Questions in C Modulus on Negative Numbers in C Multiplication table program in C using For loop Nested Loops in C Programming Examples C Program for Mean and Median of an Unsorted Array Results of Comparison Operations in C and C++ Reverse a Stack using Recursion in C Simple hash() function in C strcat() Function in C Sum of N numbers in C using For loop Use of free() function in C Write a program that produces different results in C and C++ C Function Argument and Return Values Keywords in C Bank management system in C Calendar application in C Floor() Function in C Free() Function in C How to delete a file in C How to move a text in C Remove an element from an array in C Unformatted input() and output() function in C What are linker and loader in C SJF Scheduling Program in C Socket Programming in C Structure in C Tower of Hanoi in C Union Program in C Variable Declaration in C What is Linked List in C While Loop Syntax in C fork() in C GCD program in C Branching Statements in C Comma Operator in C Control statement in C Double Specifier in C How to create a binary file in C Long int in C Palindrome Number in C Pure Virtual Function in C Run Time Polymorphism in C Types of Array in C Types of Function in C What is a buffer in C What is required in each C Program Associativity of Operators in C Bit Stuffing Program in C Actual and Formal Parameters Addition of two Numbers in C Advantages of function in C Arithmetic Progression Program in C Binomial Coefficient Program in C Difference between Array and List in C Diffie-Hellman Algorithm in C How to convert a number to words in C How to convert a string to hexadecimal in C Difference between If and Switch Statement in C C and C++ Binary Files C program that does not Suspend when Ctrl+Z is Pressed Different ways to Declare the Variable as Constant in C Range of Int in C C Program to find the size of a File FIFO Example in the C Language For loop in C Programming GCD program of two numbers in C GPA Calculator in C How to Calculate Time Complexity in C How to include graphics.h in C How to measure time taken by a function in C How to return a Pointer from a Function in C What is the main in C Addition of Matrix in C Booleans in C C Program for Extended Euclidean algorithms C Program of Fencing the Ground Ceil and Floor in C Compound Interest Program in C Displaying Array in C Distance Vector Routing Protocol Program in c Dos.h Header File in C Language DSA Program in C Explain the two-way selection in C Fee Management System in C File Operations in C Malloc function in C Multiplication Table in C Simple Programs in C Language tolower() Function in C Type Conversion in the C Why does sizeof(x++) not Increment x in C Advantages of Dynamic Memory Allocation in C Armstrong Number in C Assignment Operator Program in C Banker’s Algorithm in C Binary Search in C with Best and Worst Time Complexity Caesar Cipher Program in C Call by Value and Call by Reference in C Conditional Operator in C CRC Program in C Deadlock Detection Program in C Decimal to Binary in C Difference between If Else and Nested If Else in C Difference between Pre-increment and Post-increment in C Difference between Scope and Lifetime in C Evaluation of Arithmetic Expression in C Explain the Increment and Decrement Operators in C Fseek Function in C Functions in C How to Find Square Free Numbers in C Length of an Array Function in C OpenGL in C Projects on C language in 2023 Purpose of a Function Prototype in C Stdio.h in C Two-Dimensional array in C What is String Comparison in C C Compilers for Windows Functions and Recursion in C How to Declare Boolean in C How to Declare Character in C How to Round up a number in C How to use strlen() in C Pointer Declaration in C Algorithm for String Palindrome in C C Program to find ASCII value of a character Constant Pointer in C How to find string length in C using strlen() function Implicit and Explicit in C Indirect Recursion in C Input and Output functions in C isupper() in C Jump Statement in C Lifetime of a Variable in C Linker Error in C Language Numeric Constant in C Size of Pointer in C Square Root in C Language Static and Dynamic Memory allocation String Declaration in C Strong Number in C Symmetric Matrix in C Types of C Tokens What is a Size of Pointer in C What is Increment and Decrement Operator in C 1 2 3 4 Series Program in C Advantages and Disadvantages of C Language C Program for Polynomial Addition C Program to Count the Number of Vowels in a String C Programming Errors and Solutions Compilation Errors in C Complex C Programs Difference between Argument and Parameter in C Difference between char s[] and char *s in C Evaluation of Postfix Expression Using Stack in C Find Leftmost and Rightmost Set Bit of a Number fprintf and fscanf in C Introduction to Dynamic Array in C Print Address in C Realloc function in C Ternary Operators in C Types of Tokens in C with Examples Difference between Static and Dynamic Memory Allocation in C Addition Program in C Array Definition in C Array of Pointers in C Arrow Operator in C Average of Two Numbers in C Binary to Decimal in C Binary to Octal in C BREAK STATEMENT in C C Programming Operators Questions C Programs Asked in Interview Calculator Program in C C Program to Read and Print an Employee's Detail Using Structure Bubble Sort Algorithm in C C Program to Find Area and Perimeter of Circle C Program to Check Whether a Given Number is Even or Odd C in Roman Numerals C Program to Make a Simple Calculator Using Switch Case Insertion Sort Program in C How to take input in string in C GCC Conflicting Types in C Function Definition in C Format Specifier for Hexadecimal in C Flowchart in C Float in C Fizzbuzz Implementation in C Conditional Statement in C Conio.h functions list in C Constants in C Dynamic Array in C Decision Making Statements in C Continue Statement in C Creation of Thread in C DFS Algorithm in C Difference between parameter and arguments in C Dijkstra's Algorithm in C Leap Year Program in C Jump Statements in C Modulus Operator in C Memory Allocation in C Simple Interest Program in C Reverse Array in C Recursive Function in C Queue in C Printing Pascal’s Triangle in C Preprocessor Directives in C Perror() in C Perfect Number in C Programming Language Parameter Passing Techniques in C Pascal Triangle in C Patterm Program in C

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;

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) {
  //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;
char ch = 'a';

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.


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.
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);
 return 0;