Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C read()添加奇怪的字符_C_Posix - Fatal编程技术网

C read()添加奇怪的字符

C read()添加奇怪的字符,c,posix,C,Posix,我有这样的代码: #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <string.h> int main(){ char input[100]; while(1){ int k = read(0,input,100); if(k == 0) break; write(1,input,strle

我有这样的代码:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
int main(){
    char input[100];
    while(1){
        int k = read(0,input,100);
        if(k == 0) break;
        write(1,input,strlen(input));
    }
}
#包括
#包括
#包括
#包括
int main(){
字符输入[100];
而(1){
int k=读取(0,输入,100);
如果(k==0)中断;
写入(1,输入,strlen(输入));
}
}
在stdin上添加一些行之后,比如:
示例
示例


它通常不显示。相反,在输入块的末尾总是有一些奇怪的字符。有人能解释一下吗?

不能保证您读取的数据会被nul终止。如果不是,则您的
write
调用将写入超出所接收数据结尾的数据,仅当它找到第一个0字节或崩溃时才会停止

您知道,
input
保存
k
字节的数据,所以

write(1,input,strlen(input));
应该是

write(1,input,k);

read
读取二进制数据。它报告读取的确切字节数。除了读取这些字节,它什么也不做

C字符串不包含其长度的记录。字符串的结尾由零字节表示

因此,当
read
报告它读取
k
字节时,这正是它写入
input
的字节数。它不添加零字节,因此
input
中的内容不是字符串:它是一个字节数组,只需要第一个
k

要打印这些字节,请将数据长度传递给
write
。由于要打印出
读取的字节
读取的字节,请传递从
读取
返回的值

int k = read(0,input,100);
if(k <= 0) break;
write(1, input, k);
intk=read(0,输入,100);

如果(k)缺少空值,“不保证”的说法是温和的。read()不插入空终止符,因此只有在原始数据中,通过调用read()获得的数据中,才会有一个空终止符,并且不保证它会在获得的数据的末尾。
int k = read(0,input,99);  /*1 less to make room for the null terminator*/
if (k <= 0) break;
input[k] = 0;
fputs(input, stdout);