File Operations in C

 The steps that are involved in the file operations in C are

  1. Opening the file
  2. To perform read or write operations into the file.
  3. Closing the file.

Opening the file: 

A file has to be opened before performing the operations. Opening a file creates a link between the operating systems and the file functions.

When a request is made to the operating system for opening a file it does so by granting a request. If the request is granted, the operating system points to the structure ‘FILE’.

If the request is not granted, it returns a NULL value. 

The file has to be defined before opening the file.

The syntax for defining the file is

FILE pointervariable;
FILE *fP;

The file can be opened by using the function fopen.

The syntax is

Pointer variable=fopen(“filename”, “mode”);
fP=fopen(“P.point txt”, “w”);

The file name consists of two parts as name of the file and the extension of the file. Both these things should be separated by a period (.)

Mode is used to specify for which purpose we are opening the file. The different available modes are

  1. r: This mode opens the file for reading purposes.
  2. w: This mode opens the file for writing purposes.
  3. a: This mode opens the file for adding the data at the end of the file.
  4. wt: This mode is used for reading and writing the contents of the file.
  5. rt: This mode is used for reading and appending the data at the start of the file.
  6. at: This mode reads the data and appends the data at the end.

Note: All these modes are used to open the text files. If we want to open the binary files then the modes should be rb, wb, ab, wbt, rbt and abt.

Writing the data into the file:

If we want to write the data into the file then we can use a formatted or unformatted output function.

The formatted output function is fprintf();

The syntax is 

fprintf(file pointer, “control string”, var1, var2, …..var n);
fprintf(fp, “%d%Pf%c”, a, b, c);

The unformatted output function is fput(c);

This function is used to put a single character into the file. 

The syntax is

fputc(variable, filepointer);
fputc(ch, fP);

If we want to store only an integer value then we have to use the function fputw.

The syntax is 

fputw(variable, filepointer);
fputw(n, fP);

Reading the data from the file:

The data can be read from the file either by using formatted or unformatted input functions. The formatted input function is fscanf. 

The syntax is 

fscanf(file pointer, “control string”, &var1, &var2, ….&varn);
fscanf(fP, “%d%f%c”, &a, &b, &c);

The unformatted function is fget(c);

This function is used to read a single character from the file.

The syntax is

Variable=fgetsc(file pointer);

ch = fgetsc(fP);

If we want to read an integer value from the file then we have to use the function fgetw.

The syntax is

variable=fgetw(file pointer);
Ex: n=fgetw(fP);

Closing the file:

After performing all the operations of the file, we have to close the file. The function fclose is used to close the file. The syntax is fclose(file pointer);

Ex: fclose(fP);

C  Program to read the different values from the keyboard and store them in a file.

#include <stdio.h>
#include <stdlib.h>  // For exit()
int main() {
    FILE *fptr;     // File pointer to handle the file
    char filename[100];  // Array to store the filename
    char input[256];   // Buffer for user input
    // 1. Get filename from user
    printf("Enter the filename to store data: ");
    scanf("%s", filename);
    // 2. Open file in append mode
    fptr = fopen(filename, "a"); // 'a' appends to existing file or creates new
    if (fptr == NULL) {
        printf("Error opening file!\n");
        exit(1);  // Terminate program if error
    }
    printf("Enter values (type 'quit' to stop):\n");
    // 3. Read values from keyboard until 'quit' is entered
    while (1) { 
        // Read a line of input
        scanf("%s", input);  
        // Check if the user wants to quit
        if (strcmp(input, "quit") == 0) {
            break;
        }
        // 4. Write value and a newline to the file
        fprintf(fptr, "%s\n", input);
    }
    // 5. Close file
    fclose(fptr); 
    printf("Values successfully stored in %s\n", filename);
    return 0;
}

Output: 

Enter the filename to store data: helloworld

Enter values (type ‘quit’ to stop):

1 2  4 5  6

quit

Values successfully stored in helloworld

C Program to store some text in a file by using unformatted functions:

#include <stdio.h>
#include <stdlib.h> // For exit()
int main() {
    FILE *fptr;
    char filename[100];
    int character;
    // 1. Get the filename from the user
    printf("Enter the filename to store text: ");
    scanf("%s", filename);
    // 2. Open the file in write mode (overwrite if exists)
    fptr = fopen(filename, "w");
    if (fptr == NULL) {
        printf("Error opening file!\n");
        exit(1); 
    }
    printf("Enter your text (press Ctrl+D to finish):\n");
    // 3. Read characters until end-of-file (Ctrl+D or Ctrl+Z) is encountered
    while ((character = getc(stdin)) != EOF) {  // Read from standard input
        
        // 4. Write the character to the file
        putc(character, fptr);
    }
    // 5. Close the file
    fclose(fptr); 
    printf("Text successfully saved to %s\n", filename);
    return 0;
}

Output:

Enter the filename to store text: helloworld

Enter your text (press Ctrl+D to finish):

Hi  ..! How A are you dude..

Text successfully saved to helloworld

C Program to copy the contents of one file to another.

#include <stdio.h>
#include <stdlib.h> // For exit()
int main() {
    FILE *sourceFile, *destinationFile;
    char sourceFilename[100], destinationFilename[100];
    int character;
    // 1. Get the source filename from the user
    printf("Enter the name of the source file: ");
    scanf("%s", sourceFilename);
    // 2. Get the destination filename from the user
    printf("Enter the name of the destination file: ");
    scanf("%s", destinationFilename);
    // 3. Open the source file in read mode
    sourceFile = fopen(sourceFilename, "r");
    if (sourceFile == NULL) {
        printf("Error opening source file!\n");
        exit(1); 
    }
    // 4. Open the destination file in write mode (overwrite if exists)
    destinationFile = fopen(destinationFilename, "w");
    if (destinationFile == NULL) {
        printf("Error opening destination file!\n");
        fclose(sourceFile); // Close the source file to prevent resource leaks
        exit(1); 
    }
    // 5. Read characters from the source file until the end
    while ((character = getc(sourceFile)) != EOF) {
        // 6. Write the character to the destination file
        putc(character, destinationFile);
    }
    // 7. Close both files
    fclose(sourceFile);
    fclose(destinationFile);
    printf("File copied successfully.\n");
    return 0;
}

Output: 

Enter the name of the source file: helloworld

Enter the name of the destination file:  welcome to my world

File copied successfully.

C program to copy the contents of two files into a third file and display it.

#include <stdio.h>
#include <stdlib.h> // For exit()
int main() {
    FILE *file1, *file2, *file3;
    char filename1[100], filename2[100], filename3[100];
    int character;
    // 1. Get the first filename from the user
    printf("Enter the name of the first file: ");
    scanf("%s", filename1);
    // 2. Get the second filename from the user
    printf("Enter the name of the second file: ");
    scanf("%s", filename2);
    // 3. Get the destination filename from the user
    printf("Enter the name of the destination file: ");
    scanf("%s", filename3);
    // 4. Open the first file in read mode
    file1 = fopen(filename1, "r");
    if (file1 == NULL) {
        printf("Error opening the first file!\n");
        exit(1); 
    }
    // 5. Open the second file in read mode
    file2 = fopen(filename2, "r");
    if (file2 == NULL) {
        printf("Error opening the second file!\n");
        fclose(file1);  // Close the first file if the second can't be opened
        exit(1); 
    }
    // 6. Open the destination file in write mode (overwrite if exists)
    file3 = fopen(filename3, "w");
    if (file3 == NULL) {
        printf("Error opening the destination file!\n");
        fclose(file1);
        fclose(file2); 
        exit(1); 
    }
    // 7. Copy contents of the first file into the destination file
    while ((character = getc(file1)) != EOF) {
        putc(character, file3);
    }
    // 8. Copy contents of the second file into the destination file
    while ((character = getc(file2)) != EOF) {
        putc(character, file3);
    }
    // 9. Close all files
    fclose(file1);
    fclose(file2);
    fclose(file3);
    // 10. Reopen the destination file in read mode to display contents
    file3 = fopen(filename3, "r"); 
    if (file3 == NULL) {
        printf("Error opening the destination file for reading!\n");
        exit(1); 
    }
    printf("\nContents of the combined file:\n");
    while ((character = getc(file3)) != EOF) {
        putchar(character); // Display the character on the console
    }
    // 11. Close the destination file again (after reading)
    fclose(file3); 
    printf("\n");
    return 0;
}

Output:

Enter the name of the first file: helloworld

Enter the name of the second file: welcome

Enter the name of the destination file: myfinalfile

Contents of the combined file:

Hi..! How are you dude..

Hi..! How are you dude..

Scroll to Top