CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

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

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

  • Buffered functions and
  • Un-buffered functions.

Un-buffered functions are the raw functions that deal directly with storage devices. Whereas, buffered functions maintain 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 (seeking the file pointer) within the file
  • Close the file

Through this article, we are going to discuss the buffered functions:

Buffered functions in C for file handling

As discussed earlier, buffered functions are the functions that maintain memory buffers while handling files. This will improve the overall performance.

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

fopen function – to open a file

Step 1. To handle files, the first thing we need to do is open the file. ‘C’ provides fopen function for this purpose. When 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 the end of the file.

The syntax of fopen function looks like below:

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

The first argument is the path to the file we want to open. The second argument mode, is the mode in which the file is to open. That means, open the file in read-only mode, write-only mode, or read & write mode, etc.

In this example, we have to open a file and read the content from it. So, we will open the file as read-only. Once the file is opened, fopen will return 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 that will happen when the file is opened; is, that buffered functions maintain 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.

fread function – to read file content

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, the 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 the “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 the “size” value and “2” as the “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; the place where nothing to read.

fclose function – to close the file

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.

Working Example – Display file content on the screen

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 a read-only file. The second argument “r” means, to open the file in read-only mode. Once the file is opened, fread function will read data from the file, until it reaches the end of file. Finally, close the file using fclose function.

Place the above code into the “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 other file operations in our next articles.

// Malin

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

3 thoughts on “C Programming – Dealing with files – How to read from a file?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top