C Programs

C Programming – Files


Programs at a Glance

This section lists the programs covered under File Handling and Command Line Arguments in C. Click on a program title to jump directly to its detailed explanation.

  1. Merge Two Files into a Third File
  2. Reverse the Contents of a File
  3. Demonstration of Random Access Functions in Files
  4. Count Occurrences of a Character Using Command Line Arguments

1. Merge Two Files into a Third File


Problem Statement

Write a C program to merge the contents of two files into a third file.

Algorithm
  1. Start the program.
  2. Declare three file pointers for the two input files and the output file.
  3. Open the first file in read mode and the second file in read mode.
  4. Open the third file in write mode to store the merged contents.
  5. If any file fails to open, display an error message and stop.
  6. Read characters from the first file one by one and write them to the third file.
  7. Read characters from the second file one by one and write them to the third file.
  8. Close all three files.
  9. Display a success message.
  10. Stop the program.
C Program

#include <stdio.h>

int main() {
    FILE *f1, *f2, *f3;
    char ch;

    f1 = fopen("file1.txt", "r");
    f2 = fopen("file2.txt", "r");
    f3 = fopen("file3.txt", "w");

    if (f1 == NULL || f2 == NULL || f3 == NULL) {
        printf("File error\n");
        return 0;
    }

    while ((ch = fgetc(f1)) != EOF)
        fputc(ch, f3);

    while ((ch = fgetc(f2)) != EOF)
        fputc(ch, f3);

    fclose(f1);
    fclose(f2);
    fclose(f3);

    printf("Files merged successfully\n");
    return 0;
}
    
Sample Output

Files merged successfully
    
Explanation

The program uses fopen() to associate filenames with file pointers and checks for NULL to handle opening errors safely. Characters are copied from the first and then the second file using fgetc() to read and fputc() to write, preserving the original contents.

After copying, all files are closed using fclose() to release system resources. The third file file3.txt ends up containing the text of file1.txt immediately followed by the text of file2.txt.

2. Reverse the Contents of a File


Problem Statement

Write a C program to reverse the contents of a file.

Algorithm
  1. Start the program.
  2. Declare a file pointer and a character variable.
  3. Open the file in read mode.
  4. If the file cannot be opened, display an error and stop.
  5. Move the file pointer to the end of the file using fseek().
  6. Use ftell() to get the current position (file size in bytes).
  7. Move the file pointer backward from the end towards the beginning, one position at a time.
  8. At each position, read the character using fgetc() and print it.
  9. Close the file.
  10. Stop the program.
C Program

#include <stdio.h>

int main() {
    FILE *fp;
    char ch;
    long pos;

    fp = fopen("file.txt", "r");

    if (fp == NULL) {
        printf("File not found\n");
        return 0;
    }

    fseek(fp, 0, SEEK_END);
    pos = ftell(fp);

    while (pos--) {
        fseek(fp, pos, SEEK_SET);
        ch = fgetc(fp);
        printf("%c", ch);
    }

    fclose(fp);
    return 0;
}
    
Sample Output

(If file.txt contains: HELLO)
OLLEH
    
Explanation

The function fseek() moves the file pointer to any byte position in the file, and ftell() reports the current position, which is used here to determine the file size. Starting from the last byte and moving backwards allows the program to read characters in reverse order.

This technique demonstrates random (non-sequential) access to file contents, which is useful when only specific parts of a file need to be read or modified without scanning it from the beginning.

3. Demonstration of Random Access Functions in Files


Problem Statement

Write a C program to demonstrate random access functions in files.

Algorithm
  1. Start the program.
  2. Declare a file pointer and a character variable.
  3. Open a file in read mode.
  4. If the file cannot be opened, display an error and stop.
  5. Move the file pointer to the desired byte position using fseek().
  6. Read the character at that position using fgetc().
  7. Display the character read from the file.
  8. Close the file.
  9. Stop the program.
C Program

#include <stdio.h>

int main() {
    FILE *fp;
    char ch;

    fp = fopen("file.txt", "r");

    if (fp == NULL) {
        printf("File not found\n");
        return 0;
    }

    fseek(fp, 5, SEEK_SET);
    ch = fgetc(fp);

    printf("Character at position 6: %c\n", ch);

    fclose(fp);
    return 0;
}
    
Sample Output

(If file.txt contains: ABCDEF)
Character at position 6: F
    
Explanation

The call fseek(fp, 5, SEEK_SET) moves the file pointer to the 6th character in the file (because positions start from 0). The next fgetc() then reads exactly that character without reading earlier ones.

This example highlights how random access lets programs “jump” directly to any location in a file, which is especially useful when working with large files or fixed-size records.

4. Count Occurrences of a Character Using Command Line Arguments


Problem Statement

Write a C program to count the number of times a character occurs in a text file. The file name and character are supplied as command line arguments.

Algorithm
  1. Start the program.
  2. Use argc and argv to read the command line arguments.
  3. Check that exactly two arguments are provided: filename and character.
  4. Open the given file in read mode using the filename from argv[1].
  5. If the file cannot be opened, display an error and stop.
  6. Read the file one character at a time using fgetc().
  7. Each time the character matches the target character argv[2][0], increment a counter.
  8. After reaching end-of-file, close the file.
  9. Display how many times the character occurred in the file.
  10. Stop the program.
C Program

#include <stdio.h>

int main(int argc, char *argv[]) {
    FILE *fp;
    char ch;
    int count = 0;

    if (argc != 3) {
        printf("Usage: %s filename character\n", argv[0]);
        return 0;
    }

    fp = fopen(argv[1], "r");

    if (fp == NULL) {
        printf("File not found\n");
        return 0;
    }

    while ((ch = fgetc(fp)) != EOF) {
        if (ch == argv[2][0])
            count++;
    }

    fclose(fp);

    printf("Character '%c' occurs %d times\n", argv[2][0], count);
    return 0;
}
    
Sample Output

Command:
./program sample.txt a
Output:
Character 'a' occurs 7 times
    
Explanation

The parameters argc and argv allow the program to accept inputs from the command line instead of scanf(). Here, argv[1] holds the filename and argv[2][0] holds the character to be counted.

The file is scanned from beginning to end, and every time the current character equals the target character, the counter is increased by one. After the loop finishes, the program reports the total count, demonstrating both file handling and basic use of command line arguments.