πŸ‡―πŸ‡΅ ζ—₯本θͺž | πŸ‡ΊπŸ‡Έ English

File I/O

File operations in C: fopen, fprintf, fscanf, and fclose.

πŸ“– What you'll learn on this page
βœ… Must-know essentials
  • fopen(path, "r") / "w" / "a"
  • Always fclose
  • Check fp == NULL on failure
⭐ Read if you have time
  • Binary mode "rb" "wb"
  • fprintf, fscanf, fgets
  • File position with fseek, ftell

The File I/O Flow

When a program exits, the values it computed are normally lost. Writing them to a file makes the data persistent.
File I/O follows three steps: (1) open (fopen) β†’ (2) read or write (fprintf/fscanf) β†’ (3) close (fclose).
πŸ“‚
(1) fopen
Open the file
β†’
✏️
(2) Read/Write
fprintf / fscanf
β†’
πŸ”’
(3) fclose
Close the file
FILE *fp = fopen("data.txt", "w"); // "w" = write
if(fp == NULL){
  printf("Could not open file\n");
  return 1;
}
fprintf(fp, "Hello File!\n");    // write to the file
fclose(fp);                      // always close
Always check fopen's return value against NULL. If the file can't be opened (bad path, missing permissions), fopen returns NULL. Skip the check and your program will crash.

Writing to a File (fprintf)

fprintf is nearly identical to printf β€” it just takes a FILE pointer as its first argument.
FILE *fp = fopen("scores.txt", "w");

int scores[3] = {85, 92, 78};
for(int i = 0; i < 3; i++){
  fprintf(fp, "Student%d: %d\n", i+1, scores[i]);
}
fclose(fp);
Mode "w" (write)
Creates a new file or overwrites an existing one. Any prior content is erased.
Mode "a" (append)
Appends new content at the end of an existing file.
Mode "r" (read)
Read-only. Returns NULL if the file doesn't exist.

Reading from a File (fscanf)

fscanf is the file counterpart to scanf. Check its return value to see whether the read succeeded.
FILE *fp = fopen("numbers.txt", "r");
if(fp == NULL) return 1;

int val;
while(fscanf(fp, "%d", &val) == 1){
  printf("Read: %d\n", val);
}
fclose(fp);
fscanf's return value is the number of items successfully read. It returns EOF at end of file, so while(fscanf(...) == 1) reads all the data.

Reading Line by Line (fgets)

fgets reads an entire line as a string. It handles lines with whitespace safely, so it's often preferred over fscanf in practice.
FILE *fp = fopen("memo.txt", "r");
if(fp == NULL) return 1;

char buf[256];
int lineNo = 1;
while(fgets(buf, sizeof(buf), fp) != NULL){
  printf("%d: %s", lineNo, buf);
  lineNo++;
}
fclose(fp);
fgets is safe: it takes the buffer size (via sizeof(buf)), which prevents buffer overflows β€” a far safer choice than scanf("%s").

πŸ“ Virtual File System β€” See file operations in action

Watch what fopen, fgets, fputs, fseek, and fclose actually do, step by step. See the file pointer position, buffer contents, and how each mode ("r", "w", "a") behaves.
πŸ§ͺ Pick a scenario
Pick a scenario
// No scenario selected
πŸ“„ data.txt contents
mode: - FILE* fp: NULL pos (ftell): -
buffer (buf): -
Operation log
(Pick a scenario and press β–Ά)
πŸ’‘ Watch for: The yellow cursor (|) shows the current file pointer position. "w" empties the file on open, "a" always appends at the end, and fseek jumps to any offset.

Try It Yourself β€” File I/O

This example simulates writing to and reading from a file, all in your browser.
fileio.c
Output
Click Run...
πŸ’‘ More ideas to try

Related lessons

Basics
printf & scanf
How printf and scanf work, plus a format-specifier reference.
Advanced
Structs
Defining and using C structs, member access, and arrays of structs.
Advanced
malloc / free
Dynamic memory allocation and how to avoid leaks.
← Previous lesson
Lesson 28: Structures (struct)
Next lesson →
Lesson 30: Dynamic Memory (malloc/free)

Review Quiz

Check your understanding of this lesson.

Q1. What does the "r" argument to fopen mean?

Read-only
Write-only
Append mode

"r" is read mode. "w" is write and "a" is append.

Q2. What must you always do at the end of file operations?

free()
fclose()
return 0;

An opened file must be closed with fclose(). Otherwise, buffered data may never be flushed to disk.

Q3. What does fopen return when it fails?

0
-1
NULL

fopen returns NULL when it can't open the file. Always check the return value and handle the error.

Share this article
Share on X Share on Facebook