我试图通过管道进入读取,但在第二次输入后它会继续出现段错误。我究竟做错了什么?提前致谢。
$ ./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;
}
`