从文本文件读取错误:奇怪的'\x01' '\0' '\0' '0'序列
我正在从文件中逐行读取纯文本,具有以下功能:
int readline(FILE *in, char * buf) {
char c;
buf[0]='\0';
for (int i=0; i<BUFSIZ-1; i++) {
fread(&c,1,1,in);
if (ferror(in)) return 1;
if (feof(in)) break;
buf[i]=c;
if (c=='\n') break;
}
if (buf[BUFSIZ-1]!='\0') return 1;
return 0;
}
它正确读取 28816 个字符,然后麻烦就开始了。 它没有读取接下来的四个字符:
' ' 'f' 'o' 'r'
它读取了奇怪的事情:
'\x01' '\0' '\0' '\0'
之后,它正确读取了所有内容,直到 33080 个字符。 它没有正确读取接下来的 12 个字符,而是读取三个序列:
'\x01' '\0' '\0' '\0' '\x01' '\0' '\0' '\0' '\x01' '\0' '\0' '\0'
然后,它再次正确读取所有内容,直到某个点。
发生此问题时, (ferror(in)) 和 (feof(in)) 条件都不为 true。
您对这个问题的原因有什么想法吗?
I am reading a plain text from a file - by lines, with a following function:
int readline(FILE *in, char * buf) {
char c;
buf[0]='\0';
for (int i=0; i<BUFSIZ-1; i++) {
fread(&c,1,1,in);
if (ferror(in)) return 1;
if (feof(in)) break;
buf[i]=c;
if (c=='\n') break;
}
if (buf[BUFSIZ-1]!='\0') return 1;
return 0;
}
It reads correctly 28816 characters, and then the trouble starts.
Instead of reading the next four characters:
' ' 'f' 'o' 'r'
it reads the weird thing:
'\x01' '\0' '\0' '\0'
After that, it reads everything correctly until 33080 character.
Instead of reading next 12 characters correctly, it reads three sequences:
'\x01' '\0' '\0' '\0' '\x01' '\0' '\0' '\0' '\x01' '\0' '\0' '\0'
Then, it reads everything correctly again, until certain point.
There weren't neither (ferror(in)) nor (feof(in)) condition true when this problem occurs.
Do you have any ideas about the cause of this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它看起来不像随机数据 - 它是整数值 1 的字节序列(假设 x86 或类似的 CPU)。
我预计有两种情况之一:
1)您正在写掉缓冲区的末尾,而其他东西正在使用相同的内存
2)在程序中的其他地方,您正在将另一个数组的结尾写到内存中由缓冲区使用。
从评论中,我看到您已经对其进行了调试,似乎排除了这两个选项。请问您调试的时候是否关闭了优化?我过去在调试优化的二进制文件时有过一些棘手的经历。
It doesn't look like random data - it is the byte sequence for an integer value of 1 (assuming x86 or similar CPU).
I would expect one of two situations:
1) you're writing off the end of the buffer, and something else is using the same memory
2) somewhere else in your program, you're writing off the end of another array into the memory used by the buffer.
From the comments, I see you've debugged it, seemingly ruling out both options. I wonder whether optimisation was disabled when you were debugging? I've had tricky experiences debugging an optimised binary in the past.