File Handling in C Exercises and Solutions
File handling is a crucial skill in C programming, allowing you to read, write, and manipulate data stored in external files. This guide presents a range of exercises and solutions to hone your file handling skills, exploring various scenarios and functionalities.
1. Understanding File Operations
Before diving into specific exercises, let’s refresh our understanding of fundamental file operations in C:
- Opening Files: Use
fopen
function specifying the file path and access mode (e.g., “r” for reading, “w” for writing). - Reading Files: Use appropriate functions like
fscanf
for formatted reading orfgets
for line-by-line reading. - Writing Files: Use
fprintf
for formatted writing or direct character-by-character writing. - Closing Files: Use
fclose
function to properly close the file and release resources.
2. Basic Exercises:
2.1. Counting Lines in a File:
Write a program that reads a text file and prints the total number of lines.
Solution:
C
#include <stdio.h>
int main() {
FILE *file;
int line_count = 0;
char line[100];
// Open file for reading
file = fopen("myfile.txt", "r");
if (!file) {
printf("Error opening file!\n");
return 1;
}
// Read each line and increment counter
while (fgets(line, sizeof(line), file) != NULL) {
line_count++;
}
// Close the file
fclose(file);
// Print the total line count
printf("Total lines: %d\n", line_count);
return 0;
}
2.2. Copying a File:
Write a program that reads the contents of one file and writes them to another file.
Solution:
C
#include <stdio.h>
int main() {
FILE *source, *dest;
char buffer[100];
// Open source and destination files
source = fopen("source.txt", "r");
if (!source) {
printf("Error opening source file!\n");
return 1;
}
dest = fopen("dest.txt", "w");
if (!dest) {
printf("Error opening destination file!\n");
return 1;
}
// Read and write data chunk by chunk
while (fgets(buffer, sizeof(buffer), source) != NULL) {
fputs(buffer, dest);
}
// Close both files
fclose(source);
fclose(dest);
printf("File copied successfully!\n");
return 0;
}
3. Intermediate Exercises:
3.1. Finding a Specific Word in a File:
Write a program that reads a text file and checks if a specific word provided by the user exists within it.
Solution:
C
#include <stdio.h>
#include <string.h>
int main() {
FILE *file;
char line[100], word[50];
// Get user input for word
printf("Enter the word to search for: ");
scanf("%s", word);
// Open file for reading
file = fopen("myfile.txt", "r");
if (!file) {
printf("Error opening file!\n");
return 1;
}
// Read each line and check for word occurrence
while (fgets(line, sizeof(line), file) != NULL) {
if (strstr(line, word) != NULL) {
printf("Word found in line: %s\n", line);
break;
}
}
// Close the file and handle not found case
fclose(file);
if (!strstr(line, word)) {
printf("Word not found in the file.\n");
}
return 0;
}
3.2. Replacing Words in a File:
Solution:
C
// Get user input for words
printf("Enter the word to replace: ");
scanf("%s", old_word);
printf("Enter the new word: ");
scanf("%s", new_word);
// Open source and temporary files
file = fopen("myfile.txt", "r");
if (!file) {
printf("Error opening source file!\n");
return 1;
}
temp = fopen("temp.txt", "w");
if (!temp) {
printf("Error opening temporary file!\n");
return 1;
}
// Read and write lines with replacements
while (fgets(line, sizeof(line), file) != NULL) {
int replaced = 0;
char new_line[100];
int i, j = 0;
for (i = 0; i < strlen(line); i++) {
if (strncmp(&line[i], old_word, strlen(old_word)) == 0) {
for (int k = 0; k < strlen(new_word); k++) {
new_line[j++] = new_word[k];
}
i += strlen(old_word) - 1;
replaced = 1;
} else {
new_line[j++] = line[i];
}
}
if (replaced) {
new_line[j] = '\n';
j++;
}
fputs(new_line, temp);
}
// Close files and replace original with temporary
fclose(file);
fclose(temp);
remove("myfile.txt");
rename("temp.txt", "myfile.txt");
printf("Words replaced successfully!\n");
return 0;
}
This solution demonstrates more complex file handling concepts like opening and writing to a temporary file, modifying content based on user input, and renaming files to replace the original with the updated version.
4. Advanced Exercises:
For further challenges, consider exploring exercises involving:
- Reading and writing binary data: Working with non-textual data formats like images or databases.
- Error handling and recovery: Implementing robust mechanisms to handle file access errors and data corruption.
- Multi-file operations: Performing complex tasks across multiple files or directories.
Remember to modify these examples and experiment with different functionalities to solidify your understanding and gain confidence in handling file operations in C!