简单的问题,但由于要求而有些奇怪。
基本上,我正在尝试防止在读取文件使用文件I / O时出现缓冲区溢出,因为我正在读取缓冲区大小为32的文件。我觉得应该在某个地方回答这个问题,但是为了我的生命,搜索并不能解决问题。
我的代码的简化版本在这里:
#include <stdio.h>
#include <string.h>
#define BUFFER_SIZE 32
int main(int argc, char *argv[]) {
FILE * read_file;
char buffer[BUFFER_SIZE];
read_file = fopen("test.txt","r");
size_t num_rec = BUFFER_SIZE;
while(fread(buffer, 1,num_rec, read_file) > 0) {
printf("%s", buffer);
}
fclose(read_file);
return 0;
}
假设我正在尝试读取包含以下内容的test.txt:
This is a test file.
The file is a test.
I am having an overflow problem.
My C is not the best.
我得到这样的输出:
This is a test file.
The file is a test.
I am having an overflow problem.
My C is not the best.w problem.
My C is not the best
我了解解决此问题的最简单方法是一次读取1个字符而不是32个字符,但是,有一种方法可以解决,同时仍然一次读取32个字符吗?
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句