Post

Chapter 10: File I/O – Talking to the Filesystem

Learn how to read from and write to files in C.

Chapter 10: File I/O – Talking to the Filesystem

Table of Contents

10.1 Opening and Closing Files

Use fopen and fclose:

1
2
FILE *fp = fopen("data.txt", "r");
fclose(fp);

10.2 Reading and Writing Files

Use fprintf, fscanf, fgets, and fputs for file operations.

10.3 Exercises

  1. Write a program to write text to a file.
  2. Write a program to read a file and print its contents.
  3. What happens if you try to open a file that doesn’t exist for reading?

10.4 Solutions

10.4.1 Solution 1

1
2
3
FILE *fp = fopen("out.txt", "w");
fprintf(fp, "Hello, file!\n");
fclose(fp);

10.4.2 Solution 2

1
2
3
4
5
6
FILE *fp = fopen("out.txt", "r");
char buffer[100];
while (fgets(buffer, 100, fp)) {
    printf("%s", buffer);
}
fclose(fp);

10.4.3 Solution 3

fopen returns NULL.

10.5 What’s Coming in the Next Chapter

Next, you’ll learn about the C preprocessor!

Next Chapter → The Preprocessor – Macros and Conditional Compilation

This post is licensed under CC BY 4.0 by the author.