Reputation: 1692
How do I check if a file does not exist or it exists but I do not have permission to read it?
I know I can use stuff like perror()
or strerror(errno)
to print messages, but if I want a check that I can handle like this, how do I do that:
if (not exist) {
create file;
}
else if (no permission) {
exit;
}
This is the code I am working on. I think err
is always = -1 when the file does not exist or I do not have permission, so I don't know how to deal with it.
int fdPath, n, err;
unsigned char buffer[4096];
char *path;
// get path
path = argv[1];
// get file descriptor from opening file
fdPath = open(path, O_RDWR);
err = read(fdPath, buffer, 4096); // read file in path
Upvotes: 0
Views: 3872
Reputation: 1
On POSIX systems, you might use access to check that a file exists and/or is readable. However, be aware that if you first check the existence of a file, and later, if it does not exist, create it, there is a possible race (between checking existence & creating).
Upvotes: 2
Reputation:
Do not try to know in advance whether you can write to or read from a file -- you will have a race condition when the information changes between your check and your actual access. Do something like the following
int fd = open(path, O_RDWR|O_CREAT, 00666);
if (fd < 0) exit(1);
If you must know the reason why you can't open or create the file, you need of course some more code that checks errno
.
edit to clarify: O_CREAT
will only attempt to create the file when it's not already there. But this check is done inside the operating system, so it is an atomic operation for your process (no other process can change the situation between trying to open the file and trying to create it).
Upvotes: 5
Reputation: 311258
From the open(2)
man page:
RETURN VALUE
open(), openat(), and creat() return the new file descriptor,
or -1 if an error occurred (in
which case, errno is set appropriately).
That tells you that if you want to find out the reason the system call has failed, you need to check the errno
variable, which may be setting to something like EACCESS
(permissioned denied) or ENOENT
(no such file or directory), etc.
This looks like a reasonable example.
Upvotes: 5