C Program to Read a File

C
// C program to implement
// the above approach
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// Driver code
int main()
{
    FILE* ptr;
    char ch;

    // Opening file in reading mode
    ptr = fopen("test.txt", "r");

    if (NULL == ptr) {
        printf("file can't be opened \n");
    }

    printf("content of this file are \n");

    // Printing what is written in file
    // character by character using loop.
    do {
        ch = fgetc(ptr);
        printf("%c", ch);

        // Checking if character is not EOF.
        // If it is EOF stop reading.
    } while (ch != EOF);

    // Closing the file
    fclose(ptr);
    return 0;
}

Output

w3wiki | A computer science portal for geeks

In this program, we will read contents of the file using fgetc(). fgetc() reads characters pointed by the function pointer at that time. On each successful read, it returns the character (ASCII value) read from the stream and advances the read position to the next character. This function returns a constant EOF (-1) when there is no content to read or an unsuccessful read.




How to Read From a File in C?

File handing in C is the process in which we create, open, read, write, and close operations on a file. C language provides different functions such as fopen(), fwrite(), fread(), fseek(), fprintf(), etc. to perform input, output, and many different C file operations in our program.

In this article, we will explore how to read from a file in C using standard library functions.

Similar Reads

Read From a File in C

In C, we can read files using functions provided by the standard library such as fopen(), fgetc(), fgets(), and fread()....

C Program to Read a File

C // C program to implement // the above approach #include #include #include // Driver code int main() { FILE* ptr; char ch; // Opening file in reading mode ptr = fopen("test.txt", "r"); if (NULL == ptr) { printf("file can't be opened \n"); } printf("content of this file are \n"); // Printing what is written in file // character by character using loop. do { ch = fgetc(ptr); printf("%c", ch); // Checking if character is not EOF. // If it is EOF stop reading. } while (ch != EOF); // Closing the file fclose(ptr); return 0; }...