Easy Tutorial
❮ C Function Fputs C Function Fclose ❯

C Language Example - Reading a Line from a File

C Language Examples

Reading a line from a file.

Content of the file tutorialpro.txt:

$ cat tutorialpro.txt 
tutorialpro.org
google.com

Example

#include <stdio.h>
#include <stdlib.h> // exit() function
int main()
{
    char c[1000];
    FILE *fptr;

    if ((fptr = fopen("tutorialpro.txt", "r")) == NULL)
    {
        printf("Error! opening file");
        // Exit if the file pointer returns NULL
        exit(1);         
    }

    // Read text until a new line is encountered
    fscanf(fptr,"%[^\n]", c);

    printf("Read content:\n%s", c);
    fclose(fptr);

    return 0;
}

Output result:

Read content:
tutorialpro.org

C Language Examples

❮ C Function Fputs C Function Fclose ❯