ErrWatt
ErrWatt

Reputation: 73

Open: no such file or directory with O_CREAT

I'm trying to create a file using the open function, calling it as

dest_fd = open(fileLocation, O_RDWR | O_CREAT, 0666)

When i run the code i get:

fileLocations: /tmp/folder/file.a
open: No such file or directory

(notice that i printed the value for fileLocation to make sure that it wasn't a relative path...)

I tried to do what i found on the other topics, but it doesn't seems to work, what could it be going wrong?

Upvotes: 5

Views: 9207

Answers (1)

zwol
zwol

Reputation: 140569

When using O_CREAT, this error from open means that the parent directory of the file you're trying to create, or one of its parents, does not exist. open will not create an entire directory hierarchy for you; you have to walk up the path calling mkdir as necessary.

In this case, I would do something like

if (mkdir("/tmp/chatty", 0777) && errno != EEXIST)
   perror_exit("mkdir /tmp/chatty");
dest_fd = open("/tmp/chatty/libchatty.a", O_RDWR|O_CREAT|O_EXCL, 0666);
/* ... */

and not bother with recursing up and trying to create /tmp if the mkdir failed with ENOENT as well, because you probably don't have the privileges to do that, and in any case if /tmp doesn't exist something is horribly wrong with the computer.

Upvotes: 7

Related Questions