C FilesLesson 34Free preview
C Read Files
This lesson is part of C · All levels
Summary
Reading a file is done by opening it in "r" mode and then using fscanf to read formatted data or fgets to read a single line of text. EOF (end of file) marks no more readable data, so repetition usually stops when the read function returns EOF or NULL. It's important to make sure the file actually exists before trying to read it because the "r" mode will fail on the missing file. Once completed, the file remains mandatory to be closed with fclose.
Key points
- Fopen mode "r" returns NULL if the file is not found
- Fscanf reads the formatted data, fgets read one line to the newline
- Repeat reading usually stops when reaching EOF
- Fgets are safer because they accept a limit on the number of characters read
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.