Problem Solving using C Language

0 of 85 lessons complete (0%)

File Handling

Reading from a File

#include <stdio.h>

int main() {
  FILE *filePtr;
  char buffer[255];

  // Open the file in read mode ("r")
  filePtr = fopen("sample.txt", "r");

  // Check if the file exists
  if (filePtr == NULL) {
    printf("Error! File not found.\n");
    return 1;
  }

  // Read and display the content line by line
  while (fgets(buffer, 255, filePtr) != NULL) {
    printf("%s", buffer);
  }

  // Close the file
  fclose(filePtr);

  return 0;
}

This program reads the content from the sample.txt file created in the previous example and prints it to the console.

Explanation:

  • fgets(buffer, 255, filePtr): Reads a line of text from the file and stores it in the buffer array. The reading continues until the end of the file.
  • fclose(filePtr): Closes the file after reading is complete.