Skip to main content

Command Palette

Search for a command to run...

Basic File Handling Programming Questions

Updated
11 min read
J

I am Jyotiprakash, a deeply driven computer systems engineer, software developer, teacher, and philosopher. With a decade of professional experience, I have contributed to various cutting-edge software products in network security, mobile apps, and healthcare software at renowned companies like Oracle, Yahoo, and Epic. My academic journey has taken me to prestigious institutions such as the University of Wisconsin-Madison and BITS Pilani in India, where I consistently ranked among the top of my class.

At my core, I am a computer enthusiast with a profound interest in understanding the intricacies of computer programming. My skills are not limited to application programming in Java; I have also delved deeply into computer hardware, learning about various architectures, low-level assembly programming, Linux kernel implementation, and writing device drivers. The contributions of Linus Torvalds, Ken Thompson, and Dennis Ritchie—who revolutionized the computer industry—inspire me. I believe that real contributions to computer science are made by mastering all levels of abstraction and understanding systems inside out.

In addition to my professional pursuits, I am passionate about teaching and sharing knowledge. I have spent two years as a teaching assistant at UW Madison, where I taught complex concepts in operating systems, computer graphics, and data structures to both graduate and undergraduate students. Currently, I am an assistant professor at KIIT, Bhubaneswar, where I continue to teach computer science to undergraduate and graduate students. I am also working on writing a few free books on systems programming, as I believe in freely sharing knowledge to empower others.

Here are 10 C programming exercises that involve file handling:

  1. Word Count:

    • Read a text file and count the number of words in it.
  2. Character Frequency:

    • Read a text file and count the frequency of each character. Output the results to another file.
  3. File Copy:

    • Create a program that copies the contents of one file into another.
  4. Line Numbers:

    • Read a file and print each line with line numbers. Save the output to another file.
  5. File Encryption:

    • Implement a simple encryption algorithm to encrypt the contents of a file. Save the encrypted text to another file.
  6. File Concatenation:

    • Merge the contents of two files into a third file.
  7. Record Management:

    • Create a program that manages records. Each record can have multiple fields. Implement functionalities like add, delete, search, and modify records using a file as storage.
  8. File Search:

    • Implement a program that searches for a specific word in a text file and prints the line numbers where the word is found.
  9. CSV File Handling:

    • Read a CSV (Comma-Separated Values) file and perform operations like sorting or filtering based on specific criteria.
  10. File Deletion:

    • Write a program that deletes a specific line from a text file.

These exercises cover a range of dynamic memory allocation-related concepts and will help you practice and strengthen your skills in C programming. I have solved all of the above with explanatory comments. You should first make a sincere attempt at solving these problems before looking at the solutions.

  1. Word Count:

     #include <stdio.h>
    
     int main() {
         FILE *file;
         char ch;
         int wordCount = 0;
    
         // Open the file in read mode
         file = fopen("sample.txt", "r");
    
         // Check if file is opened successfully
         if (file == NULL) {
             printf("Could not open the file.\n");
             return 1; // Exit with an error code
         }
    
         // Count words in the file
         while ((ch = fgetc(file)) != EOF) {
             if (ch == ' ' || ch == '\n' || ch == '\t') {
                 wordCount++;
             }
         }
    
         // Close the file
         fclose(file);
    
         // Print the word count
         printf("Word count: %d\n", wordCount);
    
         return 0; // Exit successfully
     }
    
  2. Character Frequency:

     #include <stdio.h>
    
     int main() {
         FILE *inputFile, *outputFile;
         char ch;
         int frequency[256] = {0};
    
         // Open the input file in read mode
         inputFile = fopen("input.txt", "r");
    
         // Check if file is opened successfully
         if (inputFile == NULL) {
             printf("Could not open the input file.\n");
             return 1; // Exit with an error code
         }
    
         // Count character frequency
         while ((ch = fgetc(inputFile)) != EOF) {
             frequency[ch]++;
         }
    
         // Close the input file
         fclose(inputFile);
    
         // Open the output file in write mode
         outputFile = fopen("output.txt", "w");
    
         // Check if file is opened successfully
         if (outputFile == NULL) {
             printf("Could not open the output file.\n");
             return 1; // Exit with an error code
         }
    
         // Write character frequency to the output file
         for (int i = 0; i < 256; i++) {
             if (frequency[i] > 0) {
                 fprintf(outputFile, "Character '%c' occurs %d times.\n", i, frequency[i]);
             }
         }
    
         // Close the output file
         fclose(outputFile);
    
         return 0; // Exit successfully
     }
    
  3. File Copy:

     #include <stdio.h>
    
     int main() {
         FILE *sourceFile, *destinationFile;
         char ch;
    
         // Open the source file in read mode
         sourceFile = fopen("source.txt", "r");
    
         // Check if file is opened successfully
         if (sourceFile == NULL) {
             printf("Could not open the source file.\n");
             return 1; // Exit with an error code
         }
    
         // Open the destination file in write mode
         destinationFile = fopen("destination.txt", "w");
    
         // Check if file is opened successfully
         if (destinationFile == NULL) {
             printf("Could not open the destination file.\n");
             fclose(sourceFile); // Close the source file before exiting
             return 1; // Exit with an error code
         }
    
         // Copy the contents of the source file to the destination file
         while ((ch = fgetc(sourceFile)) != EOF) {
             fputc(ch, destinationFile);
         }
    
         // Close both files
         fclose(sourceFile);
         fclose(destinationFile);
    
         return 0; // Exit successfully
     }
    
  4. Line Numbers:

     #include <stdio.h>
    
     int main() {
         FILE *inputFile, *outputFile;
         char line[100];
         int lineNumber = 1;
    
         // Open the input file in read mode
         inputFile = fopen("input.txt", "r");
    
         // Check if file is opened successfully
         if (inputFile == NULL) {
             printf("Could not open the input file.\n");
             return 1; // Exit with an error code
         }
    
         // Open the output file in write mode
         outputFile = fopen("output.txt", "w");
    
         // Check if file is opened successfully
         if (outputFile == NULL) {
             printf("Could not open the output file.\n");
             fclose(inputFile); // Close the input file before exiting
             return 1; // Exit with an error code
         }
    
         // Read each line and print with line numbers
         while (fgets(line, sizeof(line), inputFile) != NULL) {
             fprintf(outputFile, "%d: %s", lineNumber, line);
             lineNumber++;
         }
    
         // Close both files
         fclose(inputFile);
         fclose(outputFile);
    
         return 0; // Exit successfully
     }
    
  5. File Encryption:

     #include <stdio.h>
    
     int main() {
         FILE *inputFile, *outputFile;
         char ch;
    
         // Open the input file in read mode
         inputFile = fopen("input.txt", "r");
    
         // Check if file is opened successfully
         if (inputFile == NULL) {
             printf("Could not open the input file.\n");
             return 1; // Exit with an error code
         }
    
         // Open the output file in write mode
         outputFile = fopen("output.txt", "w");
    
         // Check if file is opened successfully
         if (outputFile == NULL) {
             printf("Could not open the output file.\n");
             fclose(inputFile); // Close the input file before exiting
             return 1; // Exit with an error code
         }
    
         // Encrypt and write to the output file
         while ((ch = fgetc(inputFile)) != EOF) {
             fputc(ch + 1, outputFile); // Simple encryption by shifting characters by 1
         }
    
         // Close both files
         fclose(inputFile);
         fclose(outputFile);
    
         return 0; // Exit successfully
     }
    
  6. File Concatenation:

     #include <stdio.h>
    
     int main() {
         FILE *file1, *file2, *outputFile;
         char ch;
    
         // Open the first file in read mode
         file1 = fopen("file1.txt", "r");
    
         // Check if file is opened successfully
         if (file1 == NULL) {
             printf("Could not open file1.\n");
             return 1; // Exit with an error code
         }
    
         // Open the second file in read mode
         file2 = fopen("file2.txt", "r");
    
         // Check if file is opened successfully
         if (file2 == NULL) {
             printf("Could not open file2.\n");
             fclose(file1); // Close the first file before exiting
             return 1; // Exit with an error code
         }
    
         // Open the output file in write mode
         outputFile = fopen("output.txt", "w");
    
         // Check if file is opened successfully
         if (outputFile == NULL) {
             printf("Could not open the output file.\n");
             fclose(file1); // Close the first file before exiting
             fclose(file2); // Close the second file before exiting
             return 1; // Exit with an error code
         }
    
         // Copy the contents of file1 to the output file
         while ((ch = fgetc(file1)) != EOF) {
             fputc(ch, outputFile);
         }
    
         // Copy the contents of file2 to the output file
         while ((ch = fgetc(file2)) != EOF) {
             fputc(ch, outputFile);
         }
    
         // Close all files
         fclose(file1);
         fclose(file2);
         fclose(outputFile);
    
         return 0; // Exit successfully
     }
    
  7. Record Management:

     #include <stdio.h>
     #include <stdlib.h>
    
     // Define a structure for a record
     struct Record {
         int id;
         char name[50];
         float salary;
     };
    
     // Function to display the menu
     void displayMenu() {
         printf("\nRecord Management System\n");
         printf("1. Add Record\n");
         printf("2. Delete Record\n");
         printf("3. Search Record\n");
         printf("4. Modify Record\n");
         printf("5. Display All Records\n");
         printf("6. Exit\n");
         printf("Enter your choice: ");
     }
    
     // Function to add a new record
     void addRecord(FILE *file) {
         struct Record record;
    
         printf("Enter ID: ");
         scanf("%d", &record.id);
         printf("Enter name: ");
         scanf("%s", record.name);
         printf("Enter salary: ");
         scanf("%f", &record.salary);
    
         // Write the record to the file
         fseek(file, 0, SEEK_END);
         fwrite(&record, sizeof(struct Record), 1, file);
    
         printf("Record added successfully.\n");
     }
    
     // Function to delete a record
     void deleteRecord(FILE *file) {
         int targetID;
         printf("Enter the ID to delete: ");
         scanf("%d", &targetID);
    
         FILE *tempFile = fopen("temp.dat", "wb");
         struct Record record;
    
         // Copy records to the temporary file, excluding the one to delete
         while (fread(&record, sizeof(struct Record), 1, file) == 1) {
             if (record.id != targetID) {
                 fwrite(&record, sizeof(struct Record), 1, tempFile);
             }
         }
    
         fclose(file);
         fclose(tempFile);
    
         // Remove the original file
         remove("records.dat");
    
         // Rename the temporary file to the original file name
         rename("temp.dat", "records.dat");
    
         printf("Record deleted successfully.\n");
     }
    
     // Function to search for a record by ID
     void searchRecord(FILE *file) {
         int targetID;
         printf("Enter the ID to search: ");
         scanf("%d", &targetID);
    
         struct Record record;
    
         // Search for the record by ID
         fseek(file, 0, SEEK_SET);
         while (fread(&record, sizeof(struct Record), 1, file) == 1) {
             if (record.id == targetID) {
                 printf("Record found:\n");
                 printf("ID: %d, Name: %s, Salary: %.2f\n", record.id, record.name, record.salary);
                 return; // Record found, no need to continue searching
             }
         }
    
         printf("Record with ID %d not found.\n", targetID);
     }
    
     // Function to modify a record
     void modifyRecord(FILE *file) {
         int targetID;
         printf("Enter the ID to modify: ");
         scanf("%d", &targetID);
    
         struct Record record;
    
         // Search for the record by ID
         fseek(file, 0, SEEK_SET);
         while (fread(&record, sizeof(struct Record), 1, file) == 1) {
             if (record.id == targetID) {
                 printf("Enter new name: ");
                 scanf("%s", record.name);
                 printf("Enter new salary: ");
                 scanf("%f", &record.salary);
    
                 // Write the modified record back to the file
                 fseek(file, -sizeof(struct Record), SEEK_CUR);
                 fwrite(&record, sizeof(struct Record), 1, file);
    
                 printf("Record modified successfully.\n");
                 return; // Record modified, no need to continue searching
             }
         }
    
         printf("Record with ID %d not found.\n", targetID);
     }
    
     // Function to display all records
     void displayAllRecords(FILE *file) {
         struct Record record;
    
         // Display all records in the file
         fseek(file, 0, SEEK_SET);
         while (fread(&record, sizeof(struct Record), 1, file) == 1) {
             printf("ID: %d, Name: %s, Salary: %.2f\n", record.id, record.name, record.salary);
         }
     }
    
     int main() {
         FILE *file = fopen("records.dat", "ab+");
    
         // Check if the file is opened successfully
         if (file == NULL) {
             printf("Could not open the file.\n");
             return 1; // Exit with an error code
         }
    
         int choice;
    
         do {
             displayMenu();
             scanf("%d", &choice);
    
             switch (choice) {
                 case 1:
                     addRecord(file);
                     break;
                 case 2:
                     deleteRecord(file);
                     break;
                 case 3:
                     searchRecord(file);
                     break;
                 case 4:
                     modifyRecord(file);
                     break;
                 case 5:
                     displayAllRecords(file);
                     break;
                 case 6:
                     printf("Exiting the program.\n");
                     break;
                 default:
                     printf("Invalid choice. Please enter a valid option.\n");
             }
    
         } while (choice != 6);
    
         fclose(file);
    
         return 0; // Exit successfully
     }
    
  8. File Search:

     #include <stdio.h>
     #include <string.h>
    
     int main() {
         FILE *file;
         char line[100], searchWord[20];
         int lineNumber = 1;
    
         // Open the file in read mode
         file = fopen("textfile.txt", "r");
    
         // Check if file is opened successfully
         if (file == NULL) {
             printf("Could not open the file.\n");
             return 1; // Exit with an error code
         }
    
         // Get the word to search
         printf("Enter the word to search: ");
         scanf("%s", searchWord);
    
         // Search for the word and print line numbers
         while (fgets(line, sizeof(line), file) != NULL) {
             if (strstr(line, searchWord) != NULL) {
                 printf("Word found at line %d: %s", lineNumber, line);
             }
             lineNumber++;
         }
    
         // Close the file
         fclose(file);
    
         return 0; // Exit successfully
     }
    
  9. CSV File Handling:

     #include <stdio.h>
     #include <stdlib.h>
     #include <string.h>
    
     // Define a structure for an employee record
     struct Employee {
         int id;
         char name[50];
         float salary;
     };
    
     // Function to read records from a CSV file
     int readCSVFile(const char *filename, struct Employee **employees) {
         FILE *file = fopen(filename, "r");
    
         // Check if the file is opened successfully
         if (file == NULL) {
             printf("Could not open the file.\n");
             return -1; // Return an error code
         }
    
         int capacity = 10; // Initial capacity for records array
         int size = 0;      // Current size of records array
         *employees = malloc(capacity * sizeof(struct Employee));
    
         // Check if memory allocation is successful
         if (*employees == NULL) {
             printf("Memory allocation failed.\n");
             fclose(file); // Close the file before exiting
             return -1;    // Return an error code
         }
    
         // Read records from the CSV file
         while (fscanf(file, "%d,%49[^,],%f\n", &(*employees)[size].id, (*employees)[size].name, &(*employees)[size].salary) == 3) {
             size++;
    
             // Check if the records array needs to be resized
             if (size >= capacity) {
                 capacity *= 2;
                 *employees = realloc(*employees, capacity * sizeof(struct Employee));
    
                 // Check if memory reallocation is successful
                 if (*employees == NULL) {
                     printf("Memory reallocation failed.\n");
                     fclose(file); // Close the file before exiting
                     return -1;    // Return an error code
                 }
             }
         }
    
         fclose(file); // Close the file
    
         return size;  // Return the number of records read
     }
    
     // Function to print records
     void printRecords(struct Employee *employees, int size) {
         printf("ID\tName\t\tSalary\n");
         for (int i = 0; i < size; i++) {
             printf("%d\t%-15s\t%.2f\n", employees[i].id, employees[i].name, employees[i].salary);
         }
     }
    
     // Function to compare records for sorting by ID
     int compareByID(const void *a, const void *b) {
         return ((struct Employee *)a)->id - ((struct Employee *)b)->id;
     }
    
     // Function to filter records by salary threshold
     void filterBySalary(struct Employee *employees, int size, float threshold) {
         printf("\nEmployees with Salary above %.2f:\n", threshold);
         printf("ID\tName\t\tSalary\n");
         for (int i = 0; i < size; i++) {
             if (employees[i].salary > threshold) {
                 printf("%d\t%-15s\t%.2f\n", employees[i].id, employees[i].name, employees[i].salary);
             }
         }
     }
    
     int main() {
         const char *filename = "employees.csv";
         struct Employee *employees;
         int size;
    
         // Read records from the CSV file
         size = readCSVFile(filename, &employees);
    
         // Check if reading the file was successful
         if (size == -1) {
             return 1; // Exit with an error code
         }
    
         // Display the original records
         printf("Original Records:\n");
         printRecords(employees, size);
    
         // Sort records by ID
         qsort(employees, size, sizeof(struct Employee), compareByID);
         printf("\nRecords after sorting by ID:\n");
         printRecords(employees, size);
    
         // Filter records by salary threshold (example: 50000)
         filterBySalary(employees, size, 50000);
    
         // Free allocated memory
         free(employees);
    
         return 0; // Exit successfully
     }
    
  10. File Deletion:

    #include <stdio.h>
    #include <stdlib.h>
    
    int main() {
        FILE *file, *tempFile;
        char line[100];
        int lineToDelete;
    
        // Open the file in read mode
        file = fopen("data.txt", "r");
    
        // Check if file is opened successfully
        if (file == NULL) {
            printf("Could not open the file.\n");
            return 1; // Exit with an error code
        }
    
        // Open a temporary file in write mode
        tempFile = fopen("temp.txt", "w");
    
        // Check if file is opened successfully
        if (tempFile == NULL) {
            printf("Could not open the temporary file.\n");
            fclose(file); // Close the file before exiting
            return 1; // Exit with an error code
        }
    
        // Get the line number to delete
        printf("Enter the line number to delete: ");
        scanf("%d", &lineToDelete);
    
        // Copy lines to the temporary file, excluding the specified line
        int currentLine = 1;
        while (fgets(line, sizeof(line), file) != NULL) {
            if (currentLine != lineToDelete) {
                fprintf(tempFile, "%s", line);
            }
            currentLine++;
        }
    
        // Close both files
        fclose(file);
        fclose(tempFile);
    
        // Remove the original file
        remove("data.txt");
    
        // Rename the temporary file to the original file name
        rename("temp.txt", "data.txt");
    
        return 0; // Exit successfully
    }
    

More from this blog

Jyotiprakash's Blog

251 posts

I'm Jyotiprakash, a software dev and professor at KIIT, with expertise in system programming.