Monday, April 28, 2025

C Tutorial - 26 - How to Read from a File in C

# include <stdio.h>
# include <string.h>

int main( )
{
    FILE *fp ;

    char genericStorage[100];

    fp = fopen("some_file.txt", "r") ;

    if ( fp == NULL )
    {
        printf( "Unable to open some_file.txt \n" ) ;
    }
    else
    {

        printf("The File opened for reading.\n") ;

        while( fgets ( genericStorage, 100, fp ) != NULL )
        {
            printf( "%s", genericStorage ) ;
        }

        fclose(fp) ;

        printf("Data successfully read.\n");
        printf("File Closed. \n") ;
    }
    return 0;
}

Result:

The File opened for reading.
this is some content
this is second line

space is also important



Data successfully read.
File Closed.

Process returned 0 (0x0)   execution time : 0.025 s
Press any key to continue.

This C program demonstrates how to read a file using file I/O operations in C.

The program first includes two header files: stdio.h for standard input-output operations and string.h for string manipulation functions.

In the main() function, a pointer to FILE data type, fp, is declared, which will be used to store the address of the file stream. A character array genericStorage of size 100 is also declared.

Then, the fopen() function is used to open the file named "some_file.txt" in read mode with the r flag. If the file opening operation is unsuccessful, the program prints an error message, and if the file is opened successfully, a success message is printed.

Next, the program enters a while loop that reads the contents of the file line by line using the fgets() function until the end of the file is reached. The fgets() function reads up to 100 characters from the file stream fp and stores them in the character array genericStorage. The fgets() function returns NULL when it reaches the end of the file.

Inside the while loop, the contents of the character array genericStorage are printed on the console using the printf() function.

After the while loop ends, the file is closed using the fclose() function. A message is printed on the console to indicate that the file was successfully read, and the file stream is closed.

Finally, the main() function returns 0 to indicate successful program execution.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...