Eric LaRue
Eric LaRue

Reputation: 25

My open() command is not creating a new file

I am supposed to write a program that creates new files using the open() command, which, everything I read says that it's supposed to do if a file doesn't already exist.

My code is like this:

char startroom[] = "laruee.rooms/startroom.txt";
//...
int file_descriptor;
//...
file_descriptor = open(startroom, O_WRONLY | O_CREAT );
{
    fprintf(stderr, "Could not open %s\n", startroom);
    perror("in main");
    exit(1);
}

However, despite everything I've googled about this command indicating that the file should get created if it doesn't already exist, the file is not getting created. (And also from everything I googled, it appears that I am the only programmer in the universe having this problem.)

What gives?

Upvotes: 1

Views: 703

Answers (1)

Your question could be operating-system (and even file-system) specific. I guess you are running on Linux on some usual file-system like Ext4 or BTRFS.

Read open(2) & path_resolution(7). There are several reasons why an open could fail (and we cannot guess which is relevant for your computer).

It might happen that your code is not running in the conditions you want it to (working directory, user id...)

Then, improve your code as:

char startroom[] = "laruee.rooms/startroom.txt";
//...
int file_descriptor = open(startroom, O_WRONLY | O_CREAT );
if (file_descriptor < 0) {
    fprintf(stderr, "Could not open %s : %s\n", 
            startroom, strerror(errno));
    char wdbuf[256];
    if (getcwd(wdbuf, sizeof(wdbuf))
      fprintf(stderr, "in %s\n", wdbuf);
    exit(EXIT_FAILURE);
}

When using perror or strerror on errno you don't want any function which might change errno to be called after the failing syscall. On Linux with glibc the fprintf(3) function knows about %m ....

BTW, you could also strace(1) your program

Perhaps look also in your /var/log/syslog or /var/log/messages. Be sure your disk is not full (use df -h and df -i). If you have disk quotas, be sure to not overflow them. Be sure that your program is running in the directory you want it to and that current directory contains a laruee.rooms/ sub-directory; you might get it with getcwd(2) like I did above.

Particularly for server-like programs, you might want to use syslog(3).

You should read Advanced Linux Programming

BTW your open is not a command (that would be xdg-open) but a system call or at least a POSIX function

Upvotes: 2

Related Questions