1

I am writing a c file where the user runs it from the terminal (centos) and it gets on argument in argv, argv[1] = "FileName.txt". The code supposes to print the file's content only if the file does exist.

I am only allowed to use <fcntl.h> for that matter.

The code is:

int fd;
if((fd = open(path, O_CREAT | O_EXCL)) != -1){ //if file does not exist print and exit
    free(path);
    Error("File Not Found!\n");
}

char* path is already defined above. Error is a function that prints the message and then exits the program.

My problem is that it does work, but after the first run the open() function creates the file I have passed to it so when the user types again the file's name it passes through.

Going through the documentation I only found these flags to check if the file already exist. Does anyone know how to to check if a file exists without creating one?

Thank you.

eladgl
  • 69
  • 8
  • OT: If you want to print `errno` (through `perror` or use `strerror(errno)`) you must do it immediately. If you call any other function in between the value of `errno` will most likely become *indeterminate*. – Some programmer dude Nov 22 '22 at 19:31
  • @Someprogrammerdude but how will I not create the file? – eladgl Nov 22 '22 at 19:34
  • Open the file for read. If the `open` fails, the file doesn't exist. If it succeeds, read the file and print the contents. – user3386109 Nov 22 '22 at 19:34
  • As for your problem, are you looking for the something like the [`access`](https://man7.org/linux/man-pages/man2/access.2.html) function? Or what are you supposed to do with the file? If you want to open a file for reading (if it exists) just open it with `O_RDONLY`? – Some programmer dude Nov 22 '22 at 19:34
  • 1
    Also note, if you use the `O_CREAT` flag with [`open`](https://man7.org/linux/man-pages/man2/open.2.html) you *must* provide a third argument that is the file permission flags. – Some programmer dude Nov 22 '22 at 19:36
  • I expect that any answers will have a time of check to time of use (TOCTTOU) race condition, in that if you use `access` to check if a file exists or not, for example, the result might change by the time `access` has returned. Unfortunately I don't know any way around this. It would be nice if there were an `fcntl` option or an `fdreopen` that would allow you to make writable a read-only descriptor. – JohnScott Nov 22 '22 at 23:46

0 Answers0