cfile-iooutputlow-levellow-level-io

Write the contents of a file to standard-out using system calls?


I understand how to open a file and write the contents of that file into another file. I want to know how to open a file using low-level system calls open() write() read() close() to open the same file and write it to standard-out. Is this possible?

// 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);
    }
}

Solution

  • 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)