C Program To Print Contents Of File

C Program To Print Contents Of File

In this C program, we’re going to learn how to open a file and print out what’s inside it. It’s like peeking into a document using C! The program will demonstrate how C can easily handle files, making it a handy skill for dealing with information stored outside the program itself. By keeping things straightforward, this program is a great starting point for grasping the basics of working with files in C. Let’s look further and explore the contents of a file using the simplicity of C programming!

fopen() is basically functions to open the file , whereas fclose() is used to close a file in C.

#include <stdio.h> 
#include <stdlib.h> // For exit() 
  
int main() 
{ 
    FILE *fptr; 
  
    char filename[100], c; 
  
    printf("Enter the filename to open \n"); 
    scanf("%s", filename); 
  
    // Open file 
    fptr = fopen(filename, "r"); 
    if (fptr == NULL) 
    { 
        printf("Cannot open file \n"); 
        exit(0); 
    } 
  
    // Read contents from file 
    c = fgetc(fptr); 
    while (c != EOF) 
    { 
        printf ("%c", c); 
c = fgetc(fptr); 
    } 
  
    fclose(fptr); 
    return 0; 
}

Output

Enter the filename to open
a.txt
/*Contents of a.txt*/

FAQ- C Program To Print Contents Of File

Q1. How to display the contents of a file in C?

Ans. We have to Open a file using the function fopen() and then store the reference of the file in a FILE pointer. Hence, its possible to Read contents of the file using any of these functions such as fgetc(), fgets(), fscanf(), or fread(). Later, close the file using the function fclose().

Q2. How to print something from a file in C?

Ans. We create a FILE pointer variable named file.
Open the file “example.txt” in write mode (“w”) to write content using fprintf.
Close the file after writing.
Open the same file in read mode (“r”) to read content using fscanf.
Close the file after reading.

Q3. How to use Fputs in C?

Ans. fputs() is referred to as the standard C library which will write a string of characters to the file at the location indicated by the file pointer. Given below is the declaration of the fputs() function: int fputs (const char * str, FILE * stream); The fputs() function returns 0 if the string is written to the file successfully.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment