C Programming – Dealing with files – How to read from a file?

C Programming library provides good number of file handling functions to deal with files and directories or folders. Generally we can classify these functions as:

  • Buffered functions and
  • Un-buffered functions.

Un-buffered functions are the raw functions deals directly with storage devices. Whereas, buffered functions maintains memory buffers to improve the performance and reduce the number of operations with the storage devices.

With all these functions, usually we handle the files in the following way.

  • Open the file
  • Read from the file or
  • Write to the file or
  • Append to the file
  • Move within the file
  • Close the file

Through this article, let’s discuss with buffered functions:

As discussed earlier, buffered functions are the functions maintains memory buffers while handling with files. This will improve the performance.

Let’s check by writing simple programs. Below is the program which opens the file, read contents of it and display the content on the screen. That means, it works as a Linux “cat” command or MS-DOS “type” command.

Step 1. To handle with files, first thing we need to do is open the file. ‘C’ provides fopen function for this purpose. While calling the function we need to specify the purpose of opening the file. Usually these are:

  • Open file for read-only. We can’t write to the file.
  • Open file for write-only. We can’t read from the file. We can just write to the file.
  • Open the file for both read & write operations.
  • Open file in append mode. That means writing to the file from end of the file.

The syntax of fopen function looks like below:

FILE *fopen(const char *path, const char *mode);

The first argument path,  is the path to the file we want to open. The second argument mode, is the mode in which the file to open.

In this example, we have to open a file and read the contents from it. So, we will open the file as read-only. Once the file is opened, fopen will returns the pointer to the FILE structure. FILE structure holds the information about the file; buffered functions use this FILE structure pointer to deal with the files.

One more interesting thing will happen, when the file is opened. Buffered functions maintains location indicators to locate the position within the file. When the file is opened the location indicator is positioned at the beginning of the file; that is at offset “0”. If the location indicator is located at the end of the file; there will be no content to read from the file.

Step 2. Once the file is successfully opened, we need to do read, write or any other operations on it. For all these operations, FILE pointer is required. To read data from the opened file, ‘C’ provides fread function. The syntax of this function is:

size_t fread(void *ptr, size_t size, size_t ntimes, FILE *fp);

fread will read the chunks of data from the file which is previously opened through fopen function. We have to pass each chunk of data size through its second argument, size. And through ntimes argument, we have to tell, number of chunks of data to read from the file at a time.

For example: if you want to read “1024” bytes of data at a time; we can pass “1024” to size parameter and the value “1” to ntimes parameter.

Once the data is successfully read from the file, fread function will place the data into its first argument, ptr. We have to provide a storage area to store this data through its first argument.

fread function will return the number of items it reads from the file.

Once it read the data, the file location pointer moves to “ntimes * size” bytes offset position. That means, if the file location pointer is at the beginning of the file; if you call fread function with “1024” as “size” value and “2” as “ntimes” value; the file location pointer moves to “1024 * 2” bytes offset from the beginning of the file.

Step 3. We have to check the return value of fread function; to check whether the end-of-file is reached. If you requested to read nitems, but fread reads less than nitems of data; that means, it reached end-of-file; nothing to read.

Step 4. Once the operations are done with the opened file; we should close the file. ‘C’ provides fclose function to close the file which has opened through fopen function. The syntax of this function is:

int fclose(FILE *fp);

fclose will close the file. So, other programs can do file operations on the file. Upon success it will return “0” as the success value.

Let’s put all these functions together to open and read from the file. Below is the code;

// file.c
//
#include <stdio.h>
#include <string.h>
void main()
{
   FILE *fp = fopen("file.c", "r");
   if ( fp != NULL )
   {
     char data[1024] = "\0";

     while ( fread(data, 1024, 1, fp) > 0 )
     {
        printf("%s", data);
        memset(data, 0, 1024);
     }

     printf("%s", data);

     fclose(fp);
   }
}

We have used fopen function to open the file “file.c” as read-only file. The second argument “r” means, open the file in read-only mode. Once the file is opened, fread function will read data from the file, until it reaches end-of-file. Finally close the file using fclose function.

Place the above code into “file.c” file and save the file. Compile the file and run it. Observe that, it will print the content of the file “file.c”.

We will discuss about other file operations in our next article.

// Malin

3 Comments

Add a Comment

Your email address will not be published.