Reputation: 1212
I'm trying to create a C code which will create a file for which I can read or write from/to. This file can already exist, or need to be created from scratch. If it already exists within the directory, I want it to created from scratch, in other words delete all the contents.
FD = open("p.txt", O_RDWR | O_CREAT | O_TRUNC);
I've tried using that for the time being. I encounter a problem though. If the file doesn't exist, it creates it and returns a positive file descriptor.
If the file however already exists, a -1 FD is returned. So I must be missing a flag?
I assumed O_TRUNC would be enough to clear the contents of a file?
Upvotes: 0
Views: 1680
Reputation: 107739
When a Unix call returns -1, check the value of the errno
variable. It contains the reason for the error. Don't speculate as to what might be the problem until you've seen the error code. You can call strerror
or perror
to get a message describing the numerical value stored in errno
.
Also, as others have noted, when you pass O_CREAT
to open
, you must pass a third argument which determines the file's permission if it's created. (If you don't )
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
int main() {
int fd = open("p.txt", O_RDWR | O_CREAT | O_TRUNC, 0666);
if (fd == -1) {
perror("opening p.txt");
exit(1);
}
/* … */
}
Upvotes: 0