C Online Compiler
Example: C Program to Read a Line from a File
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// C Program to Read a Line from a File #include <stdio.h> #include <stdlib.h> // It's the main function of the program int main() { // Step-1 Open a file named 'hello.txt' by creating a file pointer FILE* file_string = fopen("./hello.txt", "r"); // Step-2 Buffer to store the each line of the opened file char sentence[256]; // Step-3 Check if file didn't open if (file_string == NULL) { fprintf(stderr, "Unable to open file!\n"); } // Step-4 If the file is opened then read each line of the opened file else { printf("Opened file string: 'hello.txt'\n"); printf("-----------------------------------------------------------------------\n\n"); // Iterate over each line of the file and store into 'sentence' Buffer while (fgets(sentence, sizeof(sentence), file_string)) { // Print each line of the file printf("%s", sentence); } // Close the opened file when the file stream is completed fclose(file_string); printf("\n\n-----------------------------------------------------------------------\n"); } return 0; }
Output
Clear
ADVERTISEMENTS