C program to read a file and print its contents

  • How to write a C program to read a file and print its contents?
  • Can I print the contents of a file?
  • How to print the contents of a file in C?
  • Write a C program to read the contents of a file and display it on the console?

If you are asking any of the above questions, well you have come to the right place. This article explains how you can write a C program to read a file and print its contents on the console. There is a lot of function in C to read a file’s contents, these functions are fgets, fgetc, fscanf ..etc.

Note: You should remember, the file must open in reading mode.

 

C program to read a file using fscanf in C:

The fscanf function is used to read the formatted data from the stream pointed to by stream. The arguments of the fscanf function are similar to the scanf function except that fscanf has an extra argument which is a file pointer (first argument). This file pointer tells the file from the formatted input will be read.

Syntax of fscanf():

int fscanf(FILE * restrict stream, const char * restrict format, ...);

 

Note: In fscanf, if there are insufficient arguments for the format, the behavior is undefined.

Return value of fscanf():

On success, the fscanf function returns the total number of input read and on error or at the end of the file return EOF.

 

C program to read a file using fscanf():

Now I believe you are familiar with the fscanf function. So it’s time to see the program to how to read a file using the fscanf function.

#include <stdio.h>

//Maximum size of the array
#define MAX_SIZE  32

int main()
{
    //file pointer
    FILE *fp = NULL;
    char readFileData[MAX_SIZE+MAX_SIZE] = {0};

    //open file
    fp = fopen("aticleworld.txt", "r");
    if(fp == NULL)
    {
        printf("Error in opening the file\n");
        exit(1);
    }

    //read file data
    fscanf(fp,"%s",readFileData);

    //Display read data
    puts(readFileData);

    //close the file
    fclose(fp);

    printf("Read file successfully\n");

    return 0;
}

Output:

fscanf in c

 

Code Explanation:

In the above c code, first, we opened the already created text (“aticleworld.txt”) file in reading mode and get the file pointer. Using the if condition I am verifying that the file is opened successfully or not.

//open file
fp = fopen("aticleworld.txt", "r");
if(fp == NULL)
{
    printf("Error in opening the file\n");
    exit(1);
}

 

After opening the file successfully, I have used c fscanf function to read a file (“aticleworld.txt”).

//read file data
fscanf(fp,"%s",readFileData);

 

In the last, I have used puts to display reads file data on console and fclose to close the opened file.

//Display read data
puts(readFileData);

//close the file
fclose(fp);

 

C program to read a file using fgets in C

The fgets function reads characters from the specified stream and stores them into the character array. It reads only n-1 character, where n is the specified number of characters.

It stops the reading when read newline character or (n-1) character, or encounter end-of-file. The good thing is that it writes a null character just after writing the last character into the array.

Syntax of fgets:

char *fgets(char * restrict s, int n,FILE * restrict stream);

 

Return value of fgets():

On success, the fgets function returns the string (same s parameter). On error return null pointer.

Note: If the end-of-file is encountered and no characters have been read into the “s” (character array), the contents of the “s” remain unchanged and a null pointer is returned.

 

Program to read a file using fgets():

The following C program explains how to read the contents of the file using the fgets function and display on the console screen.

#include <stdio.h>

//Maximum size of the array
#define MAX_SIZE  32

int main()
{
    //file pointer
    FILE *fp = NULL;
    char readFileData[MAX_SIZE] = {0};

    //open the file
    fp = fopen("aticleworld.txt", "r");
    if(fp == NULL)
    {
        printf("Error in opening the file\n");
        exit(1);
    }

    //Read file using fgets
    if(fgets(readFileData,MAX_SIZE,fp) == NULL)
    {
        printf("Error in reading the file\n");
        //close the file
        fclose(fp);
        exit(1);
    }

    //Display read data
    puts(readFileData);

    //close the file
    fclose(fp);

    printf("Read file successfully\n");

    return 0;
}

Output:

fgets in c

Code Explanation:

In the above c fgets example, first, we opened the already created text (“aticleworld.txt”) file in reading mode and get the file pointer. Using the if condition I am verifying that file is opened successfully or not.

//open the file
fp = fopen("aticleworld.txt", "r");
if(fp == NULL)
{
    printf("Error in opening the file\n");
    exit(1);
}

 

After opening the file successfully, I have used c fgets to read the character array from the file (“aticleworld.txt”). I have also used the if condition to check whether fgets reads a character array without error or not.

 

//Read file using fgets
if(fgets(readFileData,MAX_SIZE,fp) == NULL)
{
    printf("Error in reading the file\n");
    //close the file
    fclose(fp);
    exit(1);
}

 

In the last, I have used puts to display reads character array on console and fclose to close the opened file.

//Display read data
puts(readFileData);

//close the file
fclose(fp);

 

C program to read a file using fgetc in C

The fgetc() function read a single character from the stream and return their ASCII value. After reading the character, it advances the associated file position indicator for the stream. It takes only one argument file stream.

Syntax of fgetc():

int fgetc(FILE *stream);

 

Return value of fgetc in C:

On success, it returns the ASCII value of the character. On error or end of the file, it returns EOF.

 

C Code to read a file using fgetc:

The following C program explains how to read the contents of the file using the fgetc function and display on the console screen.

#include <stdio.h>

int main()
{
    //file pointer
    int ch = 0;
    FILE *fp = NULL;

    //open the file in read
    fp = fopen("aticleworld.txt", "r");
    if(fp == NULL)
    {
        printf("Error in opening the file\n");
        exit(1);
    }

    while( (ch=fgetc(fp)) != EOF )
    {
        //Display read character
        printf("%c", ch);
    }

    //close the file
    fclose(fp);

    printf("\n\n\nRead file successfully\n");

    return 0;
}

Output:

fgetc in c

 

 Code Analysis:

In the above c fgetc example, first, we opened the already created text (“aticleworld.txt”) file in reading mode and get the file pointer. Using the if condition I am verifying that file is opened successfully or not.

//open the file in read
fp = fopen("aticleworld.txt", "r");
if(fp == NULL)
{
    printf("Error in opening the file\n");
    exit(1);
}

 

After opening the file successfully, I have used a while loop to traverse each and every character of the file (“aticleworld.txt”). The control comes out from the while loop when fgetc get the EOF.

while( (ch=fgetc(fp)) != EOF )
 {
     //Display read character
     printf("%c", ch);
 }

 

In the last, I have used fclose to close the open file.

//close the file
fclose(fp);

 

C program to read a file using fread in C

The fread function reads nmemb elements from the given stream to the given array. for each element, fgetc is called size times (count of bytes for a single element) and the file position indicator for the stream is advanced by the number of characters read.

It is declared in stdio.h and takes four arguments. The fread function is generally used for binary files to read the binary data from the given file stream.

Syntax of fread:

size_t fread(void * restrict ptr, size_t size, size_t nmemb,
             FILE * restrict stream);

Return value of fread():

On success, it returns the number of elements successfully read. On error, it returns a number of elements less than nmemb.

Note: If the size or nmemb is zero, fread returns zero, and the contents of the array and the state of the input stream remain unchanged.

 

C program to read a file using fread:

The following C program explains how to read the contents of the file using the fread function and display it on the console screen.

#include <stdio.h>

//Maximum size of the array
#define MAX_SIZE  32

int main()
{
    //file pointer
    FILE *fp = NULL;
    char readFileData[MAX_SIZE] = {0};

    //open the file
    fp = fopen("aticleworld.txt", "r");
    if(fp == NULL)
    {
        printf("Error in opening the file\n");
        exit(1);
    }

    // Read 5 character from stream
    fread(readFileData,sizeof(char),6, fp);

    //Display read data
    puts(readFileData);

    //close the file
    fclose(fp);

    printf("Read file successfully\n");

    return 0;
}

Output:

fread in c

Code Analysis:

In the above c fread example, first, we opened the already created text (“aticleworld.txt”) file in reading mode and get the file pointer. Using the if condition I am verifying that file is opened successfully or not.

//open the file
fp = fopen("aticleworld.txt", "r");
if(fp == NULL)
{
    printf("Error in opening the file\n");
    exit(1);
}

After opening the file successfully, I have used c fread to read the file (“aticleworld.txt”) contents.

// Read 5 character from stream
fread(readFileData,sizeof(char),6, fp);

In the last, I have used puts to display reads character array on console and fclose to close the opened file.

//Display read data
puts(readFileData);

//close the file
fclose(fp);

 

Recommended Articles for you:

Leave a Reply

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