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

File I/O

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

The File I/O Flow

When a program exits, the values it computed are normally lost. Saving them to a file makes the data persistent.
File I/O takes three steps: (1) open (fopen) β†’ (2) read/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 cannot be opened (bad path, missing permissions), fopen returns NULL. Without the check, the program will crash.

Writing to a File (fprintf)

fprintf is almost identical to printf, except the first argument is a FILE pointer.
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)
Create new, or overwrite. Existing content is erased.
Mode "a" (append)
Append mode. Writes at the end of the existing file.
Mode "r" (read)
Read-only. Returns NULL if the file does not exist.

Reading from a File (fscanf)

fscanf is the file version of scanf. Use its return value to tell 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. At end-of-file it returns EOF, so while(fscanf(...) == 1) reads all the data.

Reading Line by Line (fgets)

fgets reads a whole line as a string. It handles lines containing whitespace safely, so in practice it is often preferred over fscanf.
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), preventing buffer overflows β€” a much safer input method than scanf("%s").

Try It Yourself β€” File I/O

This simulates writing and reading a file (done entirely in your browser).
fileio.c
Output
Click Run...
Advertisement

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
Structs
Next lesson β†’
malloc / free

Quick 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, "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(). Without it, data may not be flushed to disk.

Q3. What does fopen return when it fails?

0
-1
NULL

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

Share this article
Share on X Share on Facebook