[英]Writing a full-line accepted from standard-input to a file with low-level C i/o
I am writing a program that concatenates a line input from standard-input with a seperate file, and writes the combined text to an output file. 我正在编写一个程序,将标准输入的行输入与单独的文件连接起来,并将组合的文本写入输出文件。 For some reason when I type a full line of text into standard input, only the first word before whitespace is being written.
出于某种原因,当我在标准输入中输入整行文本时,只写入空格之前的第一个单词。 What's wrong with my code?
我的代码出了什么问题?
Accepting from std-in and writing: 接受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);
}
}
Further along in the program... writing the second file to output: 在程序中......将第二个文件写入输出:
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);
}
command line and output: 命令行和输出:
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:
In your first fragment, you output sizeof(p)
characters which is sizeof(char*)
(which on a 64-bit system would be 8 bytes). 在第一个片段中,输出
sizeof(p)
字符,即sizeof(char*)
(在64位系统上为8字节)。 You need to change this to at least strlen(p)
(obviously, after checking for an error and NULL
return value). 您需要将此更改为至少
strlen(p)
(显然,在检查错误和NULL
返回值之后)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.