【问题标题】:Write the contents of a file to standard-out using system calls?使用系统调用将文件的内容写入标准输出?
【发布时间】:2023-03-08 20:40:01
【问题描述】:

我了解如何打开文件并将该文件的内容写入另一个文件。我想知道如何使用低级系统调用open() write() read() close() 打开文件以打开同一个文件并将其写入标准输出。这可能吗?

// OPEN OUTPUT FILE
if((output_file = open(argv[3], O_WRONLY|O_APPEND|O_CREAT, S_IRUSR|S_IWUSR)) < 0)
{
    progress("couldn't open output");
    perror(argv[3]);
    exit(1);
}

// OPEN INPUT FILE
if((input_file1 = open(argv[1], O_RDONLY)) < 0) // open file 1
{
    progress("couldn't open file1");
    perror(argv[1]);
    close(output_file);
    exit(1);
}

// WRITE        
while((n = read(input_file1, buffer, sizeof(buffer))) > 0)
{
    if((write(output_file, buffer, n)) < 0)
    {
        perror(argv[3]);
        close(input_file1);
        close(output_file);
        exit(1);
    }
}

【问题讨论】:

  • 标准输出是 0 或 1 值。您可以尝试 write(0, ...) 或 write(1, ...)。我不记得哪个是标准输出,哪个是标准输入。

标签: c file-io output low-level low-level-io


【解决方案1】:

Standard out 只是另一个文件,它已经打开(除非它已关闭)。它的文件描述符是STDOUT_FILENO,或者fileno(stdout),通过在Posix上包含&lt;stdio.h&gt;获得:

write(STDOUT_FILENO, buffer, n)

【讨论】:

  • 谢谢!你是最棒的
猜你喜欢
  • 2016-04-21
  • 2010-11-09
  • 1970-01-01
  • 2016-05-01
  • 1970-01-01
  • 2012-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多