read()返回文件中的额外字符 [英] read() return extra characters from file
问题描述
我正在尝试从文件读取文本以进行打印..在尝试提供char缓冲区大小时,它返回了一些额外的字符..
I am trying to read text from file to print.. While trying if I give the char buffer size it returns some extra character ..
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(){
int fd = open("text.txt",O_RDONLY);
char cbuffer[100];
int a =0;
if(fd>0){
puts("File open");
ssize_t len = read(fd,cbuffer,sizeof(cbuffer));
a =printf("%s",&cbuffer);
printf("\n return data count %d",a);
}
return 0;
}
如果不是
ssize_t len = read(fd,cbuffer,sizeof(cbuffer));
到
ssize_t len = read(fd,cbuffer,10);
精确返回10个字符. 谁能解释为什么会这样?
returns 10 chars exactly . Can anyone explain why this is happening?
推荐答案
之所以会发生这种情况,是因为read()
不会对输出进行空终止.在将其用作 string 之前,您需要对目标缓冲区进行空终止.
This happens because, read()
does not null-terminate the output. You need to null-terminate the destination buffer before using it as a string.
基本上将非空终止的char
数组传递给printf()
作为%s
的参数,从而创建未定义的行为,因为可能会有超出范围的内存访问.
Basically passing a non-null terminated char
array to printf()
as the argument to %s
creates undefined behavior as there can be out of bound memory access.
实现此目标的一种方法是0
-初始化目标.这样,在read()
读取并存储有效值之后,它将被视为以空值终止.像
One way of achieving this is to 0
-initialize the destination. That way, it will be considered null-terminated after the valid values read and stored by read()
. Something like
char cbuffer[100] = {0};
可以提供帮助.
也就是说,改变
printf("%s",&cbuffer);
到
printf("%s",cbuffer);
as %s
需要一个指向以char
s为空终止的数组的指针.将数组名称传递给函数时,它会衰减到指向第一个元素的指针,因此应该可以.
as %s
expects a pointer to a null-terminated array of char
s. When you pass the array name to a function, it decays to the pointer to the first element, so you should be ok.
这篇关于read()返回文件中的额外字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!