我正在编写一个程序,它将标准输入中的行输入与单独的文件连接起来,并将组合文本写入输出文件。出于某种原因,当我在标准输入中键入一整行文本时,只会写入空格之前的第一个单词。我的代码有什么问题?
接受标准输入并写入:
// 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: