0

我了解如何打开文件并将该文件的内容写入另一个文件。我想知道如何使用低级系统调用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);
    }
}
4

1 回答 1

3

Standard out is just another file, and it's already open (unless it has been closed). Its file descriptor is STDOUT_FILENO, or alter­natively fileno(stdout), obtained by including <stdio.h> on Posix:

write(STDOUT_FILENO, buffer, n)
于 2013-10-30T10:42:06.220 回答