FREAD(3) Linux Programmer's Manual FREAD(3)
NAME
fread, fwrite - binary stream input/output
SYNOPSIS
#include
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
size_t fwrite(const void *ptr, size_t size, size_t nmemb,
FILE *stream);
DEscriptION
The function fread() reads nmemb elements of data, each size bytes long, from the
stream pointed to by stream, storing them at the location given by ptr.
The function fwrite() writes nmemb elements of data, each size bytes long, to the
stream pointed to by stream, obtaining them from the location given by ptr.
For nonlocking counterparts, see unlocked_stdio(3).
RETURN VALUE
On success, fread() and fwrite() return the number of items read or written.
This number equals the number of bytes transferred only when size is 1. If an
error occurs, or the end of the file is reached, the return value is a short item
count (or zero).
fread() does not distinguish between end-of-file and error, and callers must use
feof(3) and ferror(3) to determine which occurred.
ATTRIBUTES
For an explanation of the terms used in this section, see attributes(7).
┌──────────────────┬───────────────┬─────────┐
│Interface │ Attribute │ Value │
├──────────────────┼───────────────┼─────────┤
│fread(), fwrite() │ Thread safety │ MT-Safe │
└──────────────────┴───────────────┴─────────┘
参考文档说明fread和fwrite是线程安全的,但是也会受操作系统和gnu libc实现的影响,需要根据实际情况进行测试。
同时多线程对同一文件进行读写的情况下,需要注意中间更新的情况:
例如:
1. 文件里有个整数100
2. 线程A读取文件中的整数,减20,将结果写回文件
3. 线程B读取文件中的整数,加50,将结果写回文件
线程A和B同时工作,有可能发生以下情况:
1. 线程A读取了文件中的整数100,减20得到80
2. 同时线程B读取了文件中的整数100,加50得到150
3. 线程A将80写回文件
4. 线程B将150写回文件
这种情况下线程A的写入的结果被线程B覆盖了,产生了无效操作,可能产生与我们预期不符的结果。对于这种情况,需要保证“读取-处理-写入”过程不能被其他线程打断,可以使用MUTEX等方法改善。



