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

C File I/O

C File I/O

In the previous chapter we covered the standard input and output devices handled by C. This chapter introduces how C programmers create, open, and close text or binary files.

A file, whether text or binary, represents a series of bytes. C provides not only high-level access functions but also low-level (OS) calls to handle files on storage devices. This chapter explains the important calls for file management.

Opening a File

You can use the fopen( ) function to create a new file or open an existing one. This call initializes an object of type FILE an object of type FILE contains all the necessary information used to control the stream. Here is the prototype of this function call:



FILE *fopen( const char *filename, const char *mode );

Here,filename is a string used to name the file, and the access mode mode can have one of the following values:

Mode Description
r Open an existing text file for reading.
w Open a text file for writing. If the file does not exist, a new file is created; here your program writes from the beginning of the file. If the file exists, its contents are cleared (that is, the file is truncated to length 0).
a Open a text file for writing in append mode. If the file does not exist, a new file is created; here your program appends content to the existing file.
r+ Open a text file for both reading and writing.
w+ Open a text file for both reading and writing. If the file already exists, it is truncated to zero length; if it does not exist, a new file is created.
a+ Open a text file for both reading and writing. If the file does not exist, a new file is created. Reading starts at the beginning of the file, and writing can only be in append mode.

If you are dealing with binary files, use the following access modes instead of the ones above:



"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"

Closing a File

To close a file, use the fclose( ) function. Its prototype is as follows:



 int fclose( FILE *fp );

If the file is closed successfully,fclose( ) the function returns zero; if an error occurs while closing the file, it returns EOF. This function actually flushes buffered data, closes the file, and frees all memory used for that file. EOF is a constant defined in the header file stdio.h as a constant.

The C standard library provides various functions to read and write files character by character or as fixed-length strings.

Writing to a File

The following is the simplest function for writing a character to a stream:



int fputc( int c, FILE *fp );

function fputc() writes the character value of the argument c to the output stream pointed to by fp. If the write succeeds, it returns the character written; if an error occurs, it returns EOF. You can use the following function to write a null-terminated string to a stream:



int fputs( const char *s, FILE *fp );

function fputs() Writes the string s to the output stream pointed to by fp. If the write succeeds, it returns a nonnegative value; if an error occurs, it returns EOF. You can also use **int fprintf(FILE fp,const char format, ...) to write a string to a file. Try the following example:

Note:Please make sure you have an available tmp directory; if it does not exist, you need to create it on your computer first.

/tmp This is usually a temporary directory on Linux systems. If you are running on Windows, you need to change it to an existing directory in your local environment, for example: C:\tmp, D:\tmp, etc.

Example

#include

<

stdio.h

int

main

(

)

{

FILE

fp

=

NULL

;

fp

=

fopen

(

"

/tmp/test.txt

"

,

"

w+

"

)

;

fprintf

(

fp

,

"

This is testing for fprintf...

\

n

"

)

;

fputs

(

"

This is testing for fputs...

\

n

"

,

fp

)

;

fclose

(

fp

)

;

}

When the above code is compiled and executed, it creates a new file in the /tmp directory test.txt, and writes two lines using two different functions. Next, let's read this file.

Reading a file

The following is the simplest function for reading a single character from a file:



int fgetc( FILE * fp );

fgetc() The function reads one character from the input file pointed to by fp. It returns the character read, or on error returns EOF. The following function allows you to read a string from a stream:



char *fgets( char *buf, int n, FILE *fp );

function fgets() reads n - 1 characters from the input stream pointed to by fp. It copies the string read into the buffer buf, and appends a null character at the end to terminate the string.

If this function encounters a newline '\n' or end-of-file EOF before reading the last character, it returns only the characters read, including the newline. You can also use **int fscanf(FILE fp, const char format, ...) to read a string from a file, but it stops reading at the first space or newline.

Example

#include

<

stdio.h

int

main

(

)

{

FILE

fp

=

NULL

;

char

buff

[

255

]

;

fp

=

fopen

(

"

/tmp/test.txt

"

,

"

r

"

)

;

fscanf

(

fp

,

"

%s

"

,

buff

)

;

printf

(

"

1: %s

\

n

"

,

buff

)

;

fgets

(

buff

,

255

,

(

FILE

)

fp

)

;

printf

(

"

2: %s

\

n

"

,

buff

)

;

fgets

(

buff

,

255

,

(

FILE

)

fp

)

;

printf

(

"

3: %s

\

n

"

,

buff

)

;

fclose

(

fp

)

;

}

When the above code is compiled and executed, it reads the file created in the previous section and produces the following result:



1: This

2: is testing for fprintf...



3: This is testing for fputs...

First,fscanf() the method reads only This, because it encounters a space afterwards. Second, the call to fgets() reads the rest up to the end of the line. Finally, the call to fgets() reads the second line in full.

Binary I/O Functions

The following two functions are used for binary input and output:



size_t fread(void *ptr, size_t size, size_t count, FILE *stream);

size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);

fread and fwrite are core functions in the C standard library for block reading and writing of binary files. They operate directly on memory data blocks, avoiding the overhead of text format conversion, and are especially suitable for batch reading and writing of large files and structured data.

Parameter Description

The four parameters have the same meaning in both functions, but the data flow direction is opposite:

Parameters Type Description fread behavior fwrite behavior
ptr void* / const void* Memory buffer pointer Read destination address (written into memory) Data source address (read from memory)
size size_t Number of bytes in each data block Block size for each read Block size for each write
count size_t Number of data blocks to read or write Number of blocks expected to be read Number of blocks expected to be written
stream FILE* Pointer to the opened file Must be opened with "rb" Must be opened with "wb"

The number of bytes actually operated on is size × count. The return value is the number of blocks successfully read or written, not the number of bytes. If the return value is less than count, it may be due to end-of-file (EOF) or a read/write error, which need to be checked separately.

Binary mode vs. text mode

When using fread/fwrite, the file must be opened in binary mode; otherwise data corruption may occur.

Why binary mode is required

On Windows, text mode automatically converts the newline \n to \r\n, which breaks the integrity of binary data.

On Linux/macOS, text mode and binary mode behave the same, but cross-platform code should explicitly use the "b" flag to ensure portability.

Example

// Correct: explicitly specify binary mode

FILE

fp_read  

=

fopen

(

"data.bin"

,

"rb"

)

;

 

// Binary read

FILE

fp_write

=

fopen

(

"data.bin"

,

"wb"

)

;

 

// Binary write

// Wrong: text mode (data may be corrupted on Windows)

FILE

fp_bad

=

fopen

(

"data.bin"

,

"r"

)

;

   

// Missing the "b" flag

Comparison with text functions

Which function to choose depends on the data type and the use case:

Feature fread / fwrite fprintf / fscanf
Data handling Read and write raw memory binary data Convert by format (number <-> string)
Applicable scenarios Structures, arrays, images, audio, etc. Human-readable text such as config files, logs, and reports
Performance Fast, no conversion overhead Slow, requires parsing format strings
Precision No loss of precision Floating-point numbers may lose precision
Human-readable No (binary format) Yes (plain text format)

Data read/write flowchart

The figure below shows the data flow of fread and fwrite between a file and memory:

fread/fwrite Data Read/Write Flow

Typical Use Case

Reading and writing structure data

This is the most common use case for fread/fwrite: an entire structure can be read or written at once as a single data block.

Example

#include

#include

// Define a student structure

// Note: you must use a fixed-length array, not a char *name pointer member

typedef

struct

{

   

int

id

;

           

// Student ID

   

char

name

[

50

]

;

     

// Name (fixed array, not a pointer)

   

float

score

;

       

// Score

}

Student

;

int

main

(

)

{

   

// ===== Write the structure to a file =====

    Student s

=

{

101

,

"Alice"

,

95.5f

}

;

 

// Initialize the data

   

FILE

fp

=

fopen

(

"student.bin"

,

"wb"

)

;

   

if

(

fp

==

NULL

)

{

       

perror

(

"Failed to open file"

)

;

       

return

1

;

   

}

   

// Write the entire structure as one block of data

   

size_t

written

=

fwrite

(

&

s,

sizeof

(

Student

)

,

1

, fp

)

;

   

if

(

written

!

=

1

)

{

       

printf

(

"Write failed\n"

)

;

   

}

   

fclose

(

fp

)

;

   

// ===== Read the structure from a file =====

    fp

=

fopen

(

"student.bin"

,

"rb"

)

;

   

if

(

fp

==

NULL

)

{

       

perror

(

"Failed to open file"

)

;

       

return

1

;

   

}

    Student loaded

;

 

// Not initialized; will be filled by fread

   

size_t

read_count

=

fread

(

&

loaded,

sizeof

(

Student

)

,

1

, fp

)

;

   

if

(

read_count

!

=

1

)

{

       

printf

(

"Read failed or end of file\n"

)

;

       

fclose

(

fp

)

;

       

return

1

;

   

}

   

printf

(

"Student ID: %d, Name: %s, Score: %.1f\n"

, loaded.

id

, loaded.

name

, loaded.

score

)

;

   

fclose

(

fp

)

;

   

return

0

;

}



学号: 101, 姓名: Alice, 成绩: 95.5

A structure must not contain pointer members (such as char *name), because fwrite saves only the pointer's address value, not the string content it points to. When read back, that address is invalid, resulting in a dangling pointer. The correct approach is to use a fixed-length array, such as char name[50].

Reading and writing array data

Arrays are stored contiguously in memory, so the entire array can be read or written at once.

Example

#include

int

main

(

)

{

   

// Original data array

   

int

data

[

]

=

{

1

,

2

,

3

,

4

,

5

}

;

   

int

count

=

5

;

 

// Number of array elements

   

// ===== Write the array to a file =====

    FILE

fp

=

fopen

(

"array.bin"

,

"wb"

)

;

   

if

(

fp

==

NULL

)

{

       

perror

(

"Failed to open file"

)

;

       

return

1

;

   

}

   

// data is equivalent to &data[0], pointing to the start of the array

   

fwrite

(

data

,

sizeof

(

int

)

,

count

,

fp

)

;

   

fclose

(

fp

)

;

   

printf

(

"Wrote %d integers to array.bin\n"

,

count

)

;

   

// ===== Read the array from a file =====

   

int

buffer

[

5

]

=

{

0

}

;

 

// Initialize to 0 to make it easy to verify the read result

    fp

=

fopen

(

"array.bin"

,

"rb"

)

;

   

if

(

fp

==

NULL

)

{

       

perror

(

"Failed to open file"

)

;

       

return

1

;

   

}

   

size_t

read_count

=

fread

(

buffer

,

sizeof

(

int

)

,

count

,

fp

)

;

   

if

(

read_count

<

count

)

{

printf

(

"Incomplete read: expected %d, got %zu\n"

,

count

,

read_count

)

;

   

}

   

fclose

(

fp

)

;

   

// Print the read result

   

printf

(

"Data read: "

)

;

   

for

(

int

i

=

0

;

i

<

count

;

i

++

)

{

       

printf

(

"%d "

,

buffer

[

i

]

)

;

   

}

   

printf

(

"\n"

)

;

   

return

0

;

}



已写入 5 个整数到 array.bin

读取到的数据: 1 2 3 4 5

Batch reading and writing of large files

For large files, use a loop to read and write in chunks, avoiding loading the entire content into memory at once.

Example

#include

#include

#define BUFFER_SIZE 1024 // Read/write 1KB each time; adjust as needed

// Efficient file copy function

// Return value: 0 means success, -1 means failure

int

copy_file

(

const

char

src

,

const

char

dst

)

{

   

char

buffer

[

BUFFER_SIZE

]

;

 

// Intermediate buffer

    FILE

in

=

fopen

(

src

,

"rb"

)

;

    FILE

out

=

fopen

(

dst

,

"wb"

)

;

   

// Check whether both files were opened successfully

   

if

(

!

in

)

{

       

perror

(

"Failed to open source file"

)

;

       

return

1

;

   

}

   

if

(

!

out

)

{

       

perror

(

"Failed to open target file"

)

;

       

fclose

(

in

)

;

 

// Close the already-opened source file

       

return

1

;

   

}

   

// Read in a loop, at most BUFFER_SIZE bytes each time

   

size_t

n

;

   

while

(

(

n

=

fread

(

buffer

,

1

,

BUFFER_SIZE

,

in

)

)

0

)

{

       

// For fwrite, size=1 and count=n, ensuring the actual number of bytes read is written

       

if

(

fwrite

(

buffer

,

1

,

n

,

out

)

!=

n

)

{

           

perror

(

"Write failed"

)

;

           

fclose

(

in

)

;

           

fclose

(

out

)

;

           

return

1

;

       

}

   

}

   

// Check whether reading stopped due to an error (rather than normal EOF)

   

if

(

ferror

(

in

)

)

{

       

perror

(

"Read error"

)

;

       

fclose

(

in

)

;

       

fclose

(

out

)

;

       

return

1

;

   

}

   

fclose

(

in

)

;

   

fclose

(

out

)

;

   

printf

(

"File copied successfully: %s -> %s\n"

,

src

,

dst

)

;

   

return

0

;

}

int

main

(

)

{

   

// Usage example: copy the runoob test file

    copy_file

(

"runoob_input.bin"

,

"runoob_output.bin"

)

;

   

return

0

;

}



文件复制成功: runoob_input.bin -> runoob_output.bin

The key to this pattern is that fread returns the number of bytes actually read, and then fwrite writes only that many bytes, avoiding writing extra data at the end.

Key points to note

Check the return value

After calling fread/fwrite, you must check the return value to distinguish normal completion from error conditions.

Example

#include

int

main

(

)

{

   

int

buffer

[

100

]

;

    FILE

fp

=

fopen

(

"data.bin"

,

"rb"

)

;

   

if

(

fp

==

NULL

)

{

       

perror

(

"Failed to open file"

)

;

       

return

1

;

   

}

   

// Try to read 100 integers

   

size_t

count

=

fread

(

buffer

,

sizeof

(

int

)

,

100

,

fp

)

;

   

if

(

count

<

100

)

{

// Distinguish EOF from an error

       

if

(

feof

(

fp

)

)

{

           

printf

(

"Reached end of file; actually read %zu elements\n"

,

count

)

;

           

// At this point you can continue processing the data that was read

       

}

else

if

(

ferror

(

fp

)

)

{

           

perror

(

"An error occurred during reading"

)

;

           

fclose

(

fp

)

;

           

return

1

;

       

}

   

}

else

{

       

printf

(

"Successfully read all %zu elements\n"

,

count

)

;

   

}

   

fclose

(

fp

)

;

   

return

0

;

}



已到达文件末尾,实际读取 47 个元素

Pitfalls of structure read/write

The memory layout of a structure is affected by the compiler's alignment policy, which can cause cross-platform compatibility issues.

Inconsistent memory alignment

Different compilers or compiler options may produce different memory layouts for the same structure.

Example

#include

// Problem example: with default alignment, there are 3 bytes of padding after char

typedef

struct

{

   

char

c

;

     

// Occupies 1 byte, but there is padding after it

   

int

i

;

     

// 4-byte alignment, so it actually starts at offset 4

}

Mixed

;

// Solution 1: use pragma pack to force tight alignment

#pragma pack(push, 1) // Save the current alignment setting and set it to 1-byte alignment

typedef

struct

{

   

char

c

;

     

// Offset 0, occupies 1 byte

   

int

i

;

     

// Offset 1, occupies 4 bytes (no padding)

}

PackedMixed

;

#pragma pack(pop) // Restore the previous alignment setting

// Solution 2: manually serialize members one by one (the safest approach)

// This approach does not depend on compiler alignment and has the best cross-platform compatibility

int

main

(

)

{

   

// Print the size difference between the two structures

   

printf

(

"Default-aligned Mixed size: %zu bytes\n"

,

sizeof

(

Mixed

)

)

;

     

// Usually 8

   

printf

(

"Packed-aligned PackedMixed size: %zu bytes\n"

,

sizeof

(

PackedMixed

)

)

;

// 5

   

return

0

;

}



默认对齐 Mixed 大小: 8 字节

紧凑对齐 PackedMixed 大小: 5 字节

Recommended practices: For cross-platform or long-term storage, prefer manual serialization (reading and writing members one by one) over writing the structure directly to a file. This completely avoids alignment and byte-order issues.

No pointer members

This is one of the most common mistakes beginners make.

Example

#include

#include

#include

// Wrong example: the structure contains a pointer member

typedef

struct

{

   

int

id

;

   

char

name

;

 

// Danger! fwrite saves only the pointer value (address), not the string content

}

BadStudent

;

// Correct example: use a fixed array

typedef

struct

{

   

int

id

;

   

char

name

[

100

]

;

 

// The actual data is stored inside the structure and can be safely read and written

}

GoodStudent

;

int

main

(

)

{

   

// Demonstrate the consequences of the wrong approach

    BadStudent bs

;

    bs.

id

=

1

;

    bs.

name

=

malloc

(

50

)

;

   

strcpy

(

bs.

name

,

"RUNOOB"

)

;

   

// Write BadStudent: at this point the name pointer's address is written, but the string content is not

    FILE

fp

=

fopen

(

"bad.bin"

,

"wb"

)

;

   

fwrite

(

&

bs

,

sizeof

(

BadStudent

)

,

1

,

fp

)

;

   

fclose

(

fp

)

;

   

// Read back BadStudent: the name pointer value is an address from a previous malloc in another process and is completely invalid

    BadStudent loaded

;

    fp

=

fopen

(

"bad.bin"

,

"rb"

)

;

   

fread

(

&

loaded

,

sizeof

(

BadStudent

)

,

1

,

fp

)

;

   

fclose

(

fp

)

;

   

// loaded.name is a dangling pointer; accessing it causes undefined behavior!

   

free

(

bs.

name

)

;

   

printf

(

"Demonstration complete, but the name pointer loaded is invalid\n"

)

;

   

return

0

;

}



演示完成,但 load 出来的 name 指针是无效的

Buffer flushing

The C standard library's I/O is buffered, so critical data needs to be explicitly flushed to ensure persistence.

Example

#include

int

main

(

)

{

    FILE

fp

=

fopen

(

"critical.bin"

,

"wb"

)

;

   

if

(

fp

==

NULL

)

{

       

perror

(

"Failed to open file"

)

;

       

return

1

;

   

}

   

int

data

[

]

=

{

1

,

2

,

3

,

4

,

5

}

;

   

fwrite

(

data

,

sizeof

(

int

)

,

5

,

fp

)

;

   

// Method 1: explicitly flush the buffer so data is written to disk immediately

   

fflush

(

fp

)

;

   

printf

(

"Use fflush to force a flush to disk\n"

)

;

   

// Method 2: flush automatically when the file is closed (recommended)

   

// fclose internally calls fflush automatically

   

fclose

(

fp

)

;

   

printf

(

"fclose also flushes the buffer automatically\n"

)

;

   

return

0

;

}



使用 fflush 强制刷新到磁盘

fclose 也会自动刷新缓冲区

File pointer positioning

Using fseek and ftell together enables random access to a file, reading data at a specified position as needed.

Example

#include

typedef

struct

{

   

int

id

;

   

char

name

[

50

]

;

   

float

score

;

}

Student

;

int

main

(

)

{

    FILE

fp

=

fopen

(

"students.bin"

,

"rb"

)

;

   

if

(

fp

==

NULL

)

{

       

perror

(

"Failed to open file"

)

;

       

return

1

;

   

}

   

// Jump to the end of the file to get its size

   

fseek

(

fp

,

0

,

SEEK_END

)

;

   

long

file_size

=

ftell

(

fp

)

;

   

printf

(

"File size: %ld bytes\n"

,

file_size

)

;

   

// Calculate how many structure records are in the file

   

long

record_count

=

file_size

/

sizeof

(

Student

)

;

   

printf

(

"Contains %ld student records\n"

,

record_count

)

;

   

// Jump to the 6th structure (index starts at 0, offset = 5 * sizeof(Student))

   

fseek

(

fp

,

sizeof

(

Student

)

5

,

SEEK_SET

)

;

    Student s

;

   

fread

(

&

s

,

sizeof

(

Student

)

,

1

,

fp

)

;

   

printf

(

"The 6th record: id=%d, name=%s\n"

,

s.

id

,

s.

name

)

;

   

fclose

(

fp

)

;

   

return

0

;

}



文件大小: 6000 字节

包含 100 条学生记录

第 6 条记录: id=106, name=RUNOOB

Summary of common errors

The table below summarizes the most common problems and the correct practices when using fread/fwrite:

Error types Symptom Correct approach
File pointer not checked Calling fread directly after fopen fails, causing a crash Always check fp != NULL
Ignoring binary mode On Windows, binary data is corrupted by newline conversion Use "rb" / "wb"
Confusing block count with byte count Treating the return value as a byte count, leading to logic errors Remember the return value is the block count; byte count = return value * size
Buffer overflow Insufficient allocated space, writing out of bounds Ensure buffer space >= size * count
Structure contains pointers After reading back, the pointer address is invalid, resulting in a dangling pointer Use fixed arrays or manually serialize each member
Ignoring error checks Not distinguishing EOF from a read error, resulting in incomplete data Check the return value and use feof() / ferror() to determine the cause
Data not synchronized A program crash causes buffered data to be lost Call fflush(fp) after writing critical data