消除线程中的缓冲区溢出(C)

马克斯·琼斯

简单的问题,但由于要求而有些奇怪。

基本上,我正在尝试防止在读取文件使用文件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个字符吗?

乔纳森·莱夫勒

fread()函数读取二进制数据,并且不添加空字节。您需要告诉您printf()要打印多少个字节,应该是所返回的数字fread()

size_t nbytes;
while((nbytes = fread(buffer, 1, num_rec, read_file)) > 0)
    printf("%.*s", (int)nbytes, buffer);

注意fread()返回a size_t,但是.*in操作printf()需要一个int;。所以要转换(尽管它有可能从保存值fread()中的int,并使用该无铸造)。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章