程序问答   发布时间:2022-06-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了写入 bin 文件时出错大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决写入 bin 文件时出错?

开发过程中遇到写入 bin 文件时出错的问题如何解决?下面主要结合日常开发的经验,给出你关于写入 bin 文件时出错的解决方法建议,希望对你解决写入 bin 文件时出错有所启发或帮助;
struct Seats seats[12];
file* inp;
file* opt;
int counter = 1;
char option;
if ((inp = fopen("seats.bin","rb")) == NulL) {// open file to read
    printf("file dID not open!");
    exit(0);
}
fread(&seats,sizeof(struct Seats),12,inp);// save file data to struct array

//later in the code
opt = fopen("seats.bin","w");
fwrite(seats,opt);
fclose(inp);

我从 bin 文件中读取数据没有问题。但是,当我尝试写入文件时,它会存储随机值,从而在我再次启动程序时无法读取。 如果你们知道这个问题,我将不胜感激

解决方法

如果您在 windows 上,重要的是在这一wb 上写 w 而不是只写 opt = fopen("seats.bin","wb"); 来引用 binary 文件:

struct Seats seats[12];
FILE* inp;
FILE* opt;
int counter = 1;
char option;
if ((inp = fopen("seats.bin","rb")) == NULL) {// open file to read
    printf("file did not open!");
    exit(0);
}
fread(&seats,sizeof(struct Seats),12,inp);// save file data to struct array

//later in the code
opt = fopen("seats.bin","wb");//w for write,b for binary
fwrite(seats,opt);
fclose(inp);
,

你需要检查你实际阅读了多少,并且只写了那么多。否则,如果您阅读的内容少于预期,您就会写出 seats 中的任何垃圾。

size_t num_read = fread(seats,inp);

// later

fwrite(seats,num_read,opt);

还有...

  • 检查 fopen 是否有效。
  • 使用 wb 编写二进制文件,例如 rb。它只在 Windows 机器上很重要。

大佬总结

以上是大佬教程为你收集整理的写入 bin 文件时出错全部内容,希望文章能够帮你解决写入 bin 文件时出错所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。