【问题标题】:Writing a full-line accepted from standard-input to a file with low-level C i/o将标准输入接受的全行写入具有低级 C i/o 的文件
【发布时间】:2013-11-11 17:54:01
【问题描述】:

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

接受标准输入并写入:

// 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: 

【问题讨论】:

  • 将低级 POSIX I/O 函数(read(2)、write(2))与 C stdio 函数(fgets、fprintf、...)混合使用被认为是不好的风格。 (如果你在同一个打开的文件中混合它们,由于 stdio 的缓冲,这实际上不太可能给出你预期的结果)
  • 除此之外,除非您知道自己在做什么,否则不要使用 read(2)/write(2)。您必须进行大量错误检查,例如 I/O 错误或中断调用 (EINTR) 的信号。

标签: c low-level low-level-io low-level-code


【解决方案1】:

在您的第一个片段中,您输出sizeof(p) 字符,即sizeof(char*)(在 64 位系统上为 8 个字节)。您需要将其更改为至少strlen(p)(显然,在检查错误和NULL 返回值之后)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-09
    • 2013-11-11
    • 2017-09-20
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多