So I'm doing some very basic work with opening and closing files in C.
I noticed that when I run the following code, I get strange output:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdlib.h>
main()
{
// first get rid of existing input.txt, which is guaranteed to exist
pid_t pid = fork();
//child code
if (pid == 0) {
char* command[4] = {"rm", "-f", "input.txt", NULL};
execvp(command[0], command);
}
// parent code
else {
int status;
wait(&status);
}
// initialize file descriptor
int fd;
// open input.txt with given flags
int flags = O_RDWR | O_CREAT;
fd = open("input.txt", flags);
// debug
fprintf(stderr,"The openval is %d\n", fd);
// now close it
int closeval = close(fd);
// debug
fprintf(stderr,"The closeval is %d\n", closeval);
// try to re-open-it with different flags
flags = O_RDONLY;
fd = open("input.txt", flags);
// debug
fprintf(stderr,"The new openval is %d\n", fd);
}
Output:
The openval is 3
The closeval is 0
The new openval is -1
The first and second lines of output make sense to me. My big question is, why can I not open the file a second time?
I figured at first that it might be because I was requesting to open it the second time using the following flags:
flags = O_RDWR;
My thought was that requesting write permissions would somehow be messed up by the previous open (even though that shouldn't be the case because I closed it, right?). So i tried the version from above that only asks to read the file, and still no luck.
Is opening, closing, and then re-opening files like that just not an option?
Edit: Here is the errno testing code and output
if(fd == -1) {
char* error = strerror(errno);
fprintf(stderr,"%s\n",error);
}
Output:
Permission denied