gpt4 book ai didi

c++ - 将某些字符和结构写入文件并读回时,fread 和 fwrite 出现问题

转载 作者:太空宇宙 更新时间:2023-11-04 02:01:46 27 4
gpt4 key购买 nike

我想将三个字符写入一个文件,然后是一个结构,然后再写入一个字符。最后我想读取结构之前的字符、结构本身、结构之后的字符并将它们显示在屏幕上。

 struct stuff{
int a;
int b;
};

int main(){

FILE * fp = fopen("input.txt", "w+");
char charA = 'z';
char charB = 's';
char charC = 'q';
char charD = 'e';

//create a struct of type stuff
stuff s;
s.a = 123;
s.b = 2111;

//fwrite three first chars
fwrite(&charA, 1, sizeof(char), fp);
fwrite(&charB, 1, sizeof(char), fp);
fwrite(&charC, 1, sizeof(char), fp);
//fwrite the struct
fwrite(&s, 1, sizeof(struct stuff), fp);
//fwrite the last char
fwrite(&charD, 1, sizeof(char), fp);

//read the char before the struct, the struct itself,
// and the char after the struct
char expectedCharC;
stuff expectedStructS;
char expectedCharD;

fseek(fp, sizeof(struct stuff) + sizeof(char), SEEK_END);
fread(&expectedCharC, 1, sizeof(char), fp);
fread(&expectedStructS, 1, sizeof(struct stuff), fp);
fseek(fp, sizeof(char)*3 + sizeof(struct stuff), SEEK_SET);
fread(&expectedCharD, 1, sizeof(char), fp);

cout<<expectedCharC<<" "<<expectedStructS.a<<" ";
cout<<expectedStructS.b<<" "<<expectedCharD<<endl;

fclose(fp);

return 0;
}

而不是这个结果:

q 123 2111 e

我得到这个结果:

4197174 0 e

我不知道我做错了什么。我正在将字节写入文件,读回它们并将它们显示在屏幕上。出了什么问题?

提前谢谢你

最佳答案

哇,您的代码中有很多问题。让我们一一解决。

  1. 如 unwind 所述,您用于打开文件的模式似乎与您尝试执行的操作不正确。其一,您正在尝试从以只写方式打开的文件中读取

  2. 您错误地使用了 fwrite。它是 fwrite(指向数据的指针,每个数据的大小,数据的数量,FILE 指针);

  3. 您错误地使用了 fseek。我发现您对 offset 参数感到困惑。此偏移量定义了与指定为 fseek 的最后一个参数的 origin有符号距离。因此,如果您在 SEEK_END,您应该通过将 offset 设置为负数来向后移动。

我自己完成了这些更改,现在可以使用了。输出:q 123 2111 e

这是一个不错的小东西 website对你也是。帮我解决了你的问题。

感谢阅读。

关于c++ - 将某些字符和结构写入文件并读回时,fread 和 fwrite 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26489919/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com