无法使用 fread 从文件读取数据
unsigned long int nextOffset, currOffset, len;
nextOffset = read offset from file (eg. 15)
currOffset = read prev offset from file (eg. 0 )
len = nextOffset-currOffset;
str = malloc((int)len);
fread(str,(int)(len)-1,1,dataFile);
str[(int)len]='\0';
rowAddr = ftell(tempDataFile);
fwrite(&rowAddr,sizeof(unsigned long int),1,tempOffsetFile);
fwrite(str,(int)(len)-1,1,tempDataFile);
free(str);
由于某种原因,我无法使用 fread 从数据文件中读取数据。我对其进行了调试,发现 string str 显示随机数据。当我执行此 strlen(str) 操作时,它显示 1709936 .....
这段代码可能有什么问题..所有这些文件都以二进制模式打开...
unsigned long int nextOffset, currOffset, len;
nextOffset = read offset from file (eg. 15)
currOffset = read prev offset from file (eg. 0 )
len = nextOffset-currOffset;
str = malloc((int)len);
fread(str,(int)(len)-1,1,dataFile);
str[(int)len]='\0';
rowAddr = ftell(tempDataFile);
fwrite(&rowAddr,sizeof(unsigned long int),1,tempOffsetFile);
fwrite(str,(int)(len)-1,1,tempDataFile);
free(str);
for some reason i'm not able to read from datafile using fread.. i debugged it and what i found was that the striing str is showing random data.. when i did this strlen(str) it shows 1709936.....
what is possibly wrong with this code.. all these files are opeend in binary mode...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Ptival 所说的。
但最严重的问题是,如果您分配
n
字节,它们的编号从 0 到n
-1。您将字节n
设置为零,并且该字节超出了您malloc()
的末尾。因此,您可能无意中破坏了其他一些数据。 C 不会阻止你这样搬起石头砸自己的脚。否则,根据您所说的需要,您的代码似乎没有太大问题。我对其进行了一些充实,并将其全部封装在一个小 shell 脚本中以便于运行。脚本:
输出:
希望这有帮助。
What Ptival said.
But the most eggregious problem is that if you allocate
n
bytes, they are numbered from 0 ton
-1. You're setting byten
to zero, and that byte is beyond the end of what you'vemalloc()
ed. So you're probably unintentionally stomping on some other data. C won't keep you from shooting yourself in the foot this way.Otherwise, based on what you said you needed, there doesn't seem to be much wrong with your code. I fleshed it out a bit, and wrapped it all in a little shell script for easy running. The script:
The output:
Hope this helps.