I have some code which iteratively appends data to a file and looks similar to:
for(int i=0; i<number; i++){
FILE *log_file;
char name[50];
sprintf(name,"something_%d.log",i);
log_file=fopen(name,"a");
if(log_file == NULL){
printf("ERROR cannot open file %s",name);
abort();
}
/* Write stuff to file */
fclose(log_file);
}
Seems simple enough right? If the file exists and I have permission to write to it, it proceeds as normal; if the file does not exist and I have permission to write files in the directory, it creates the file as normal. WRONG! Somehow, when I come across a particular file name (MINI_3f_1_0.log) the program cannot create/open the file and yields log_file = NULL. Obviously this is not my entire code, and the worst thing is that I cannot reproduce this problem with a simple program as shown.
I have already spent a few hours trying to track down what is going on, and so far I am 100% sure of the following:
- The file is declared, opened, and closed within the same scope
- A file of the same name is not open in any other function/the entire program
- I have permission to read/write in the directory
- Trying to open the file out of the iterative order produces the same error when it is done in the same routine
Any guidance you guys/gals can give me would be greatly appreciated. If you have come across anything like this in your experience, how did you fix it?
As suggested by Mat in the comments,running the code in a different directory did not produce the error. There is something likely wrong with the file system and needs to be looked into by the sys-admin.