Opening and Reading a Text File in C

0
541

In most of the practically used programs   information needs to be stored in computer memory device for future use and analysis. But the common console input/output programs are not capable of storing data in computer hard disk. In order to create a file on computer memory device and to extract the information from the file, the concept of file handling in C plays vital role. In this tutorial post, I have described the process of opening and reading a text file using file handling.

The tutorial post consists of two separeate source codes for opening and reading a text file along with the brief expalnation of each and algorithm. The algorithm presented gives the ides for writing of source codes in any high level language. The algorithm for opening and reading a text file in C has given below:

Algorithm for Opening and Reading the text file

  • For opening a text file
  1. Start
  2. Declare variable and file pointer
  3. Assign file pointer to fopen() function with write format
  4. If file is not opened, print error message
  5. Else give the content using loop
  6. Close the file
  7. Stop
  • For Reading a Text File
  1. Start
  2. Declare variables and file pointer
  3. Open the file
  4. If the file is not opened print error massage
  5. Print the content of the text file using loop
  6. Close the file
  7. Stop

Source Code for Opening and Reading the text file

  • For Opening a Text File

 

The above source code is simple to understand and friendly due to the use of multiple comment lines. It includes a single header file: stdiio.h which controls the basic input/output function in the C program.

In the program, fp is the file pointer which is assigned to fopen(“file.txt”, “w”) to open a file named ‘file’ of .txt  format in write mode. If the file doesn’t exist on the computer memory device, it creates a new vacant file. The statement if (!fp)  is included to check the error in opening and reading a text file process.

Finally, the opened file needs to be closed and it is done with the function fclose(fp).

  • For Reading a Text File

 

The working mechanism of this source code is similar to above source code. But, it uses the function fopen() to open the file.txt file in reading mode i.e. function is called with “file.txt” and “r” as argument. After the file is opened in reading mode, the content of file.txt is displayed on the screen and file is closed.

Both the source codes are well tested and error free. When the codes for opening and reading a text using file handing are executed in Code::Blocks compiler, the first code opens the file on hard disk and the second reads the content of the file.

As far as I think, the above source codes for opening and reading a text in C are useful in understanding the file handing process. You can use this source codes as a part of your C programming project to open file.

LEAVE A REPLY

Please enter your comment!
Please enter your name here