我正在编写一个程序,它将标准输入的行输入与单独的文件连接起来,并将组合的文本写入输出文件。出于某种原因,当我在标准输入中输入整行文本时,只写入空格之前的第一个单词。我的代码出了什么问题?
接受std-in和写作:
// check for stdinput flag
if(strcmp(argv[1], "-") == 0) // use standard-in for input file 1
{
printf("Type your text and then hit enter: ");
p = fgets(userInput, sizeof(userInput), stdin);
if (write(output_file, userInput, sizeof(p)) < 0) // write stdin to output file
{
perror(argv[4]);
close(output_file);
exit(1);
}
}
在程序中......将第二个文件写入输出:
else // open file2 and assign to file-handler, then output to file
{
if((input_file2 = open(argv[2], O_RDONLY)) < 0)
{
perror(argv[2]);
close(output_file); // close the opened output file handler
exit(1);
}
while((n = read(input_file2, buffer, sizeof(buffer))) > 0)
{
if((write(output_file, buffer, n)) < 0)
{
perror(argv[3]);
close(input_file2);
close(output_file);
exit(1);
}
}
close(input_file2);
}
命令行和输出:
server1{user25}35: program - file2 outputfile
Type your text and then hit enter: THIS IS MY TEXT FROM STDIN
server1{user25}36: cat outputfile
THISthis is the text in file2
server1{user25}37:
答案 0 :(得分:2)
在第一个片段中,输出sizeof(p)
个字符sizeof(char*)
(在64位系统上为8个字节)。您需要将此更改为至少strlen(p)
(显然,在检查错误和NULL
返回值后)。