Files are used to store data permanently on hard disk. C programming supports built in library function to interact with files and directories. I have compiled a list of file handling exercises with solution for beginners and intermediate programmers.
Required knowledge
Basic C programming, Structures, Pointers, File Handling
Quick overview of files and directories
In programming we use variables to store data. Variables are fast and quick at data storage and manipulation, but are volatile. They lose their value after program termination.
In our programming life, there exists situations where we want persistent data. The data should persist even after program termination and can be used anytime later. A file is a physical storage location on disk where data is persisted (stored permanently). We use file to store data permanently on hard disk. A directory is a logical logical path used to organize files. A file exists within a directory.
We perform only three operations on file:
- Open a file
- Process file (read, write, modify)
- Save and close file
So let us begin our file handling journey, with the following list of file handling exercises and solutions. Try to solve as much as you can.
List of file handling exercises
- Write a C program to create a file and write contents, save and close the file.
- Write a C program to read file contents and display on console.
- Write a C program to read numbers from a file and write even, odd and prime numbers to separate file.
- Write a C program to append content to a file.
- Write a C program to compare two files.
- Write a C program to copy contents from one file to another file.
- Write a C program to merge two file to third file.
- Write a C program to count characters, words and lines in a text file.
- Write a C program to remove a word from text file.
- Write a C program to remove specific line from a text file.
- Write a C program to remove empty lines from a text file.
- Write a C program to find occurrence of a word in a text file.
- Write a C program to count occurrences of a word in a text file.
- Write a C program to count occurrences of all words in a text file.
- Write a C program to find and replace a word in a text file.
- Write a C program to replace specific line in a text file.
- Write a C program to print source code of same program.
- Write a C program to convert uppercase to lowercase character and vice versa in a text file.
- Write a C program to find properties of a file using stat() function.
- Write a C program to check if a file or directory exists.
- Write a C program to rename a file using rename() function.
- Write a C program to list all files and sub-directories recursively.
Drop your query, suggestion or feedback related to file handling exercises/programs in comments section.
Happy coding 😉