我试图通过管道读取,但在第二次输入后它仍然出现段错误。我究竟做错了什么?提前致谢。
$ ./read < <(python -c 'print "BBA\nBBADD\n",')
Please enter your first name:
buf=
BBA
BBA
Please enter your last name:
buf=
Segmentation fault (core dumped)
我附上了read的代码作为引用,重要的部分是read()
//read.c
#include <stdio.h>
#include <string.h>
void prompt_name(char *name, char *msg){
char buf[4096];
puts(msg);
read(0, buf, sizeof buf);
puts("buf=");
puts(buf);
*strchr(buf, '\n') = 0;
puts(buf);
strncpy(name, buf, 20);
puts(name);
}
void prompt_full_name(char *fullname) {
char last[20];
char first[20];
prompt_name(first, "Please enter your first name: ");
prompt_name(last, "Please enter your last name: ");
strcpy(fullname, first);
strcat(fullname, " ");
strcat(fullname, last);
}
int main(int argc, char **argv){
char fullname[42];
prompt_full_name(fullname);
printf("Welcome, %s\n", fullname);
return 0;
}
`
最佳答案
read
对字符串一无所知,因此它只是愉快地读取 sizeof(buf)
字符,而不会以 NUL 结尾 buf
。调用 puts(buf) 会导致未定义的行为。
您不应该将此类低级函数用于简单的字符串 I/O;更喜欢 getline
。如果您确实想使用read
,则读取较小的 block ,检查每次调用的返回值并使用它;它告诉您阅读了多少内容。
关于python - 通过管道传输到 unistd.h 读取段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13291199/