I have a c program that is trying to read in a file. Using the access() command it says the file is there but fopen() returns NULL and errno says the file does not exist.
A truncated snippet of code:
FILE *fp;
char *filename = strdup(git_dir);
strcat(filename, "/HEAD");
printf(git_dir);
printf(":");
printf(filename);
printf(":");
if (access(filename, F_OK)) {
printf("Y U NO OPEN:");
}
fp = fopen(filename, "r");
if (fp == NULL) {
printf(strerror(errno));
return;
}
As you might tell from the code, this is trying to open the .git/HEADS file of a git repository. The particular repository this is failing on was cloned into a subdir of another repository and then added as a submodule. I do not have problems that were cloned by running the git submodule update command.
The above code does not print “Y U NO OPEN:” but it does print out the strerror(). I printed the filename to the screen and opened the file with less and it opens fine. This program is generating my zsh prompt, so I imagine it is being run by my user, and the permissions on the file are
-rw-r--r-- 1 ben users 23 Jun 30 13:32 HEAD
Any suggestions?
You can’t do this:
You’re appending the string “/HEAD” to filename, but filename only has room for the content of
git_dir. Thus you’re writing past the buffer, overwriting memory, and possibly causing havoc, and all kinds of unpredictable behavior can occur.Do this instead:
Keep in mind that stdout is normally line-buffered as well. This means that if you do
printf("Y U NO OPEN:");, you might not see the output immediately. Print a newline, \n, to flush the output.