简体   繁体   English

在C中读取二进制文件的奇怪之处

[英]Strangeness in reading a binary file in C

I've defined a binary file like this in C 我已经在C中定义了这样的二进制文件

FILE *gfp;
gfp = fopen(gridfiles, "wb");

The variable gridfiles stores the name of the file, and has been defined earlier. 变量gridfiles存储文件的名称,并且已在前面定义。 Now I write out two variables into the file. 现在,我将两个变量写到文件中。

for(yy = 0; yy < nfiley; yy++) {
   for(xx = 0; xx < nfilex; xx++) {
      filebx = beguv + xx*1E3;
      fileby = enduv - yy*1E3;
      fwrite(&filebx, sizeof(filebx), 1, gfp);
      fwrite(&fileby, sizeof(fileby), 1, gfp);
   }
}

If right after this code I 如果此代码之后我

fseek(gfp, 0, SEEK_SET);
fread(&filebx, sizeof(filebx), 1, gfp);
fread(&fileby, sizeof(fileby), 1, gfp);
fprintf(stderr, "%f %f", filebx, fileby);

my output is 我的输出是

1000 15000

for the first two, which is as expected. 对于前两个,这是预期的。

But if after some assorted other code (that doesn't involve these files at all) I repeat the fseek() etc., my output is 但是,如果在一些其他代码(根本不涉及这些文件)之后,我重复fseek()等,我的输出是

14000 14000

regardless of what I do. 不管我做什么 I've been trying to figure this out for a while now... anyone know what I'm doing wrong? 我已经尝试了一段时间了……有人知道我在做什么错吗?

It's Undefined Behaviour to read from a stream which has been opened in write mode. 从以写模式打开的流中进行读取是未定义的行为 You should make it: 您应该做到:

gfp = fopen(gridfiles, "wb+");

if you plan to both read and write. 如果您打算同时读写。

Also, as pointed out by @Kyle Jones in the comments above, you should get into the habit of checking the return status of fread / fwrite when doing file I/O - this would have caught your problem a lot earlier. 另外,正如@Kyle Jones在上述评论中指出的那样,您应该养成在执行文件I / O时检查fread / fwrite返回状态的习惯-这会早点解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM