Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Language Examples - Read a Line from a File

C Language Examples - Read a Line from a File

C Language Examples C Language Examples

Read a line from a file.

Contents of the file runoob.txt:



$ cat runoob.txt 

runoob.com

google.com

Example

#include

<

stdio.h

#include

<

stdlib.h

// exit() function

int

main

(

)

{

char

c

[

1000

]

;

FILE

fptr

;

if

(

(

fptr

=

fopen

(

"

runoob.txt

"

,

"

r

"

)

)

==

NULL

)

{

printf

(

"

Error! opening file

"

)

;

// Exit if the file pointer returns NULL

exit

(

1

)

;

}

// Read text until the beginning of a new line is encountered

fscanf

(

fptr

,

"

%[^

\

n]

"

,

c

)

;

printf

(

"

Content read:

\

n%s

"

,

c

)

;

fclose

(

fptr

)

;

return

0

;

}

The output is:



Read content:

runoob.com

C Language Examples C Language Examples