读取和写入不同的值
大家好,这基本上是我上一个问题的延伸。我已经在文件中写入了短整型值,使用
short int x= 254;
FILE * f1 = fopen("infile" ,"w");
fwrite (&x , 1 , sizeof(short int ) , f1 );
它工作正常,但是当我尝试检索这样的值时,
short int y ;
fread(&y , 2, 1 ,f1);
printf("%d" , y);
它给了我答案 8180,下次是 12276 等等...我实际上应该做什么
我想在我的文件中存储短整数然后一一检索它们我做错了吗请指导我
Hello every one this is basically extension to my previous question. i have write the short int value in file using
short int x= 254;
FILE * f1 = fopen("infile" ,"w");
fwrite (&x , 1 , sizeof(short int ) , f1 );
it working fine but when i tried to retrieve value like this
short int y ;
fread(&y , 2, 1 ,f1);
printf("%d" , y);
it gave me answer 8180 and next time 12276 so on... what should i do
actually I want to store short integers in my file and then retrieve them one by one am i doing it wrong kindly guide me
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最有可能的是,您没有在写入和读取之间关闭并重新打开文件。我建议创建一个执行这两个操作的小函数,首先写入,然后关闭和刷新,然后读取。看看你会得到什么样的结果。另外,请确保您使用的是二进制模式。
Most likey you aren't closing and reopening the file between writing and reading. I would suggest creating a small function that does both actions, first writing, then closing and flushing, then reading. See what kind of results you get with that. Also, make sure you are using binary mode.
如果您想从刚刚写入的文件中读回,则需要使用“w+”选项打开它以允许读取和写入。然后,您需要返回到文件的开头:
或者,您可以将读/写作为单独的操作:
请注意,在原始代码中,您没有检查 fread 的返回值来检查您是否实际上从中读取了任何内容文件。如果您这样做了,您会看到它返回 0 表示它读取了 0 个字节。如果您没有从文件中读取任何内容并且没有初始化
y
,那么它可能只是一个随机数。If you want to read back from the file you just wrote to, you need to open it with "w+" options to allow you to read and write. You then need to seek back to the beginning of the file:
Alternatively, you could read / write as separate operations:
Note that in your original code you weren't checking the return value of fread to check whether you'd actually read anything from the file. If you'd done that you'd have seen it was returning 0 to indicate that it read 0 bytes. If you're not reading anything from the file and you're not initialising
y
then it's likely to just be a random number.我同意乔恩·凯奇的回答(支持他,而不是我!)
还要注意(很久以前),Windows/DOS 系统需要用“wb”、“rb”而不是“w”和“r”打开二进制文件'。我不确定情况是否仍然如此,但尝试一下是没有问题的。
这里有一些代码可以让事情变得更清楚:
对于读取部分:
另外,请记住文件内的位置在每次读/写后都会递增。在阅读之前您可能想回到文件的开头。通过关闭/重新打开文件(如 Jon 答案中所示)或通过使用以下命令开始查找来执行此操作:
完整代码:
I agree with Jon Cage answer (upvote him, not me!)
Also note that (a long time ago), Windows/DOS systems needed binary files to be opened with 'wb', 'rb' instead of 'w' and 'r'. I'm not sure it is still the case, but there's no problem trying.
Here's a bit of code to get things more clear:
And for the reading part:
Also, remember that the position inside the file is incremented after each read/write. You might want to get back to the start of the file before reading. Do this either by closing/reopening the file as in Jon answer or by seeking to the start using:
Full code: