Question

Here is how I tried to write a file using C under Linux

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>

int main(int argc, char *argv[])
{
    printf("Sharing a file using fork() command.\n");


    int file;

    //man 2 open page
    errno = 0;
    file = open("/home/anu/Desktop/Codes/Share-File/bin/Debug/file.txt",O_WRONLY | O_APPEND);

    if(-1 == file)
    {
        printf("\nOpen() failed with error [%s]\n",strerror(errno));
        return 1;
    }
    else
    {
        printf("\nOpen() Successful\n");
        if (write(1, "This will be output to standard out\n", 36) != 36)
        {
            write(2, "There was an error writing to standard out\n", 44);
            return -1;
        }
    }

    return 0;
}

The file opens successfully, however the data i provide is not appended. Where have I gone wrong? P.S. Please don't point to using fopen() etc. I want to achieve the intended result with the write() function only. Thanks.

Was it helpful?

Solution

First of all, it's better to use the predefined constants for standard fds STDIN_FILENO,STDOUT_FILENO,STDERR_FILENO.

Also, you have to close an opened file when you're done writing to it. Anyway: You're not actually writing to the file you've opened in this example. What output did you expect?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top