连续两次 fwrites 操作

Mad*_*ddy 2 c fwrite fread

我在写模式下打开了一个文件,如下所示:

int a = 10;
char b = 'm';
int y = 0;
char z;

FILE *fp = NULL;
fp = fopen("/config/gps_backup.dat","w");
Run Code Online (Sandbox Code Playgroud)

我正在对文件执行两个变量的 frwite(第一个是整数,第二个是字符),如下所示:

fwrite(&a,1,sizeof(int),fp);
fwrite(&b,1,sizeof(char),fp);
Run Code Online (Sandbox Code Playgroud)
  1. 两个连续的 fwrite 操作会不会互相覆盖
  2. 如果没有,两个连续的 fread 操作是否可以正确填充到我的变量中

例如:

fread(&y,1,sizeof(int),fp);
fread(&z,1,sizeof(char),fp);
Run Code Online (Sandbox Code Playgroud)

如果连续 fread 操作完成,y 和 z 变量是否可以保存 10 和 'm' 的值。

Jay*_*Jay 5

两个连续的 fread 或 fwrite 应该不会造成任何问题,只要它们不是并行完成的。

系统将在 FILE * 中维护查找指针,并确保您在连续的 fwrites 和 freads 期间获得正确的数据写入和读取。

您可以参考手册页了解更多详细信息。

它在 RETURN VALUES 部分清楚地说明了以下内容

 The functions fread() and fwrite() advance the file position indicator
 for the stream by the number of bytes read or written.  They return the
 number of objects read or written.  If an error occurs, or the end-of-
 file is reached, the return value is a short object count (or zero).
Run Code Online (Sandbox Code Playgroud)