File Handling in C

File Handling in C. File Handling in C Tutorial. Learn File Handling in C.
File Handling in C

What is File Handling in C ?

File handling in C is a way to work with files, which allows a program to read data from, write data to, and perform other operations on files. Files are a fundamental way to store and retrieve information on a computer system.

File handling is used for various purposes, including:

  1. Storing Data: It allows programs to save data in a structured format for later retrieval.
  2. Processing Data: Programs often need to read data from external sources (like text files, databases, etc.) and process it.
  3. Logging: Many programs use file handling to create log files to record events and activities.
  4. Configuration Files: Programs often read configuration settings from files.
  5. Persistent Storage: It enables programs to store data permanently, so it can be used across different program runs.

File Handling Functions in C

Here is a table of commonly used file handling functions in C:

Sr. No.FunctionDescriptionHeader File
1fopen()Opens a file for specified mode (read/write).<stdio.h>
2fclose()Closes a file.<stdio.h>
3fprintf()Writes formatted data to a file.<stdio.h>
4fscanf()Reads formatted data from a file.<stdio.h>
5fputc()Writes a character to a file.<stdio.h>
6fgetc()Reads a character from a file.<stdio.h>
7fgets()Reads a line from a file.<stdio.h>
8fputs()Writes a string to a file.<stdio.h>
9fwrite()Writes data to a file.<stdio.h>
10fread()Reads data from a file.<stdio.h>
11feof()Tests for end-of-file on a file.<stdio.h>
12rewind()Sets the file position indicator to the beginning of the file.<stdio.h>
13ftell()Returns the current file position indicator.<stdio.h>
14fseek()Sets the file position indicator.<stdio.h>
15remove()Deletes a file.<stdio.h>
16rename()Renames a file.<stdio.h>

1. fopen()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");
    
    if (file != NULL) {
        fprintf(file, "Hello, World!\n");
        fclose(file);
    }
    
    return 0;
}

Output:

Hello, World!

Explanation:

  • The fopen() function is used to open a file. In this case, it opens a file named “example.txt” in write mode (“w”).
  • If the file is successfully opened, it returns a pointer to a FILE structure. Otherwise, it returns NULL.
  • The fprintf() function is used to write formatted data to the file.
  • Finally, fclose() is used to close the file.

2. fclose()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");
    
    if (file != NULL) {
        fprintf(file, "Hello, World!\n");
        fclose(file); // Closing the file
        printf("File closed successfully.\n");
    } else {
        printf("Unable to open the file.\n");
    }
    
    return 0;
}

Output:

example.txt is closed.

Explanation:

  • fclose() is used to close a file that has been opened.
  • In above example, the file “example.txt” is opened, written to, and then closed. It displays a message indicating whether the file was closed successfully or if there was an issue opening it.

3. fprintf()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");
    
    if (file != NULL) {
        fprintf(file, "42\n"); // Writing data
        fclose(file);
        
        file = fopen("example.txt", "r");
        if (file != NULL) {
            int num;
            fscanf(file, "%d", &num); // Reading data
            fclose(file);
            printf("Read: %d\n", num);
        }
    }
    
    return 0;
}

example.txt file content:

Consider the file example.txt has value “42” stored inside it.

Output:

Read: 42

Explanation:

In above example, we demonstrates both fprintf() for writing data and fscanf() for reading data from the same file.

4. fscanf()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    int num;
    
    if (file != NULL) {
        fscanf(file, "%d", &num);
        fclose(file);
        printf("Read: %d\n", num);
    }
    
    return 0;
}

example.txt file content:

Consider the file example.txt has value “42” stored inside it.

Output:

Read: 42

Explanation:

  • This example opens “example.txt” in read mode (“r”).
  • It then uses fscanf() to read an integer from the file.
  • The value 42 is stored in the variable num, and it is printed to the console.

5. fputc()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");
    
    if (file != NULL) {
        fputc('A', file);
        fclose(file);
    }
    
    return 0;
}

Output:

A

Explanation:

The fputc() function is used to write a single character to the file.

So, character “A” is now written in the example.txt file.

6. fgetc()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    
    if (file != NULL) {
        int ch = fgetc(file);
        if (ch != EOF) {
            printf("Read: %c\n", ch);
        }
        fclose(file);
    }
    
    return 0;
}

example.txt file content:

Consider the file example.txt has character “B” stored inside it.

Output:

Read: B

Explanation:

  • fgetc() reads a single character from the file.
  • The EOF (End of File) constant is used to check if the end of the file has been reached.

7. fgets()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    
    if (file != NULL) {
        char buffer[100];
        fgets(buffer, sizeof(buffer), file);
        printf("Read: %s", buffer);
        fclose(file);
    }
    
    return 0;
}

example.txt file content:

Consider the file example.txt has line “This is a sample line” stored inside it.

Output:

Read: This is a sample line.

Explanation:

fgets() reads a line of text from the file into the character array buffer.

8. fputs()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "w");
    
    if (file != NULL) {
        fputs("This is a sample line.\n", file);
        fclose(file);
    }
    
    return 0;
}

Output:

This is a sample line.

Explanation:

fputs() writes a string to the file.

So, line “This is a sample line.” is now written in the example.txt file.

9. fwrite()

#include <stdio.h>

struct Employee {
    char name[50];
    int employee_id;
};

int main() {
    FILE *file = fopen("employees.bin", "wb");
    
    if (file != NULL) {
        struct Employee emp1 = {"Alice", 101};
        struct Employee emp2 = {"Bob", 102};
        
        fwrite(&emp1, sizeof(struct Employee), 1, file);
        fwrite(&emp2, sizeof(struct Employee), 1, file);
        
        fclose(file);
    }
    
    return 0;
}

Output:

No output will be displayed on the console. This program doesn’t include any printf or similar statements to produce console output. Instead, it writes the data directly to the “employees.bin” binary file. You can verify the results by opening and inspecting the “employees.bin” file using a binary file viewer or by reading and displaying the data using another C program or don’t worry because we will be opening the file and viewing the content in the next example down below !!!

This contents of the file will be in binary format which might look like this:

416c6963650065000000000000000065000000
426f6200660000000000000000000066000000
  • Each record consists of two parts: the name (up to 50 characters) and the employee ID (an integer).
  • In binary format, character data is represented as ASCII values.
  • “Alice” is represented as 416c69636500, where 41 is ‘A’, 6c is ‘l’, 69 is ‘i’, 63 is ‘c’, 65 is ‘e’, and 00 is the null terminator.
  • The employee ID 101 is represented as 65000000 in little-endian byte order.
  • Similarly, “Bob” is represented as 426f620066000000 (with null padding) and the employee ID 102 as 66000000.

Explanation:

  • fwrite() is used to write binary data to a file.
  • In this example, we define a struct Employee and write two employee records to a binary file.

10. fread()

#include <stdio.h>

struct Employee {
    char name[50];
    int employee_id;
};

int main() {
    FILE *file = fopen("employees.bin", "rb");
    
    if (file != NULL) {
        struct Employee emp1, emp2;
        
        fread(&emp1, sizeof(struct Employee), 1, file);
        fread(&emp2, sizeof(struct Employee), 1, file);
        
        printf("Employee 1: %s, ID: %d\n", emp1.name, emp1.employee_id);
        printf("Employee 2: %s, ID: %d\n", emp2.name, emp2.employee_id);
        
        fclose(file);
    }
    
    return 0;
}

Output:

Displaying contents from the example.bin file:

Employee 1: Alice, ID: 101
Employee 2: Bob, ID: 102

Explanation:

  • fread() is used to read binary data from a file.
  • In above example, we read the employee records from the binary file created in the previous example and print the information.

11. feof()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    
    if (file != NULL) {
        while (!feof(file)) {
            char ch = fgetc(file);
            if (ch != EOF) {
                printf("%c", ch);
            }
        }
        fclose(file);
    }
    
    return 0;
}

Output:

This is a sample text.

Explanation:

  • feof() is used to test for the end of the file.
  • In above example, we use it in a while loop to read characters from the file until the end of the file is reached.

12. rewind()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    
    if (file != NULL) {
        // Read and print the file content once
        char ch;
        while ((ch = fgetc(file)) != EOF) {
            printf("%c", ch);
        }
        
        // Rewind the file to the beginning
        rewind(file);
        
        // Read and print the file content again
        printf("\n\nAfter Rewind:\n");
        while ((ch = fgetc(file)) != EOF) {
            printf("%c", ch);
        }
        
        fclose(file);
    }
    
    return 0;
}

example.txt file content:

Consider the file example.txt has line “This is a sample line” stored inside it.

Output:

This is a sample text.

After Rewind:
This is a sample text.

Explanation:

rewind() sets the file position indicator to the beginning of the file, allowing you to read the file from the start again.

13. ftell()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    
    if (file != NULL) {
        long position;
        
        // Get the current file position
        position = ftell(file);
        printf("Current position: %ld\n", position);
        
        // Read and print the file content
        char ch;
        while ((ch = fgetc(file)) != EOF) {
            printf("%c", ch);
        }
        
        // Get the new file position
        position = ftell(file);
        printf("\nNew position: %ld\n", position);
        
        fclose(file);
    }
    
    return 0;
}

example.txt file content:

Consider the file example.txt has line “This is a sample line” stored inside it.

Output:

Current position: 0
This is a sample text.
New position: 23

Explanation:

  • ftell() is used to get the current file position, which is the number of bytes from the beginning of the file.
  • In above example, we use it to display the current position before and after reading the file content.

14. fseek()

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    
    if (file != NULL) {
        // Seek to the 10th byte from the beginning
        fseek(file, 10, SEEK_SET);
        
        // Read and print the file content from the new position
        char ch;
        while ((ch = fgetc(file)) != EOF) {
            printf("%c", ch);
        }
        
        fclose(file);
    }
    
    return 0;
}

example.txt file content:

Consider the file example.txt has line “This is a sample line” stored inside it.

Output:

sample text.

Explanation:

  • fseek() is used to set the file position to a specified offset.
  • In above example, we seek to the 10th byte from the beginning and read the file content from that position.

15. remove()

#include <stdio.h>

int main() {
    if (remove("example.txt") == 0) {
        printf("File deleted successfully.\n");
    } else {
        printf("Unable to delete the file.\n");
    }
    
    return 0;
}

Output:

example.txt is deleted.

Explanation:

  • remove() is used to delete a file.
  • In this example, we attempt to delete the file “example.txt” and display a message based on the success or failure of the operation.

16. rename()

#include <stdio.h>

int main() {
    if (rename("oldfile.txt", "newfile.txt") == 0) {
        printf("File renamed successfully.\n");
    } else {
        printf("Unable to rename the file.\n");
    }
    
    return 0;
}

Output:

oldfile.txt renamed to newfile.txt.

Explanation:

  • rename() is used to rename a file.
  • In above example, we attempt to rename “oldfile.txt” to “newfile.txt” and display a message based on the success or failure of the operation.

More: