I have a Lunix C program that store configuration parameters in a text file.
I read from the text file using
FILE *file = fopen(filename, "r"):
and write to the file using
FILE *file = fopen(filename, "w"):
I am getting a problem where the text file is cleared, it is blank the next time I come to read it.
I understand that when the file is opened for write it gets overwritten, my program stores the contents of the file after it has read it in and writes it back out.
It does in the main write it out correctly, but occasionally I will find that the text file is blank.
My initial thoughts were that this may be because the program was unsafly stopped, mid way through writing to the file leaving it blank or there were 2 instances of the program running and as one open it for writing, the other reads it in, meaning it would read in a blank file and then overwrite it with a blank file when it writes it out.
After some testing this does not seem to be the case.
This leaves me unsure as to what is causing the text file to be cleared.
Does anyone have any ideas?
or has anyone seen something like this before?
Thanks, any help will be appreciated.
char text_lines[200][54];
void read_in_text_file()
{
char line[128];
int counter = 0;
int length;
static const char filename[] = "config.txt";
FILE *file = fopen(filename,"r");
if (file==NULL){
perror ("Error opening file");
printf("Error opening file\n");
exit(0);
}
else{
while ( fgets ( line, sizeof line, file ) != NULL)
{
sprintf(text_lines[counter],"%s",line);
length = zstrlen(text_lines[counter]);
if(text_lines[counter][length-1] == '\n')
{
text_lines[counter][length-1] = '\0';
}
counter = counter + 1;
}
number_of_lines = counter;
fclose(file);
}
}
void print_to_text_file()
{
pthread_mutex_lock(&lock);
int counter;
static const char filename[] = "config.txt";
FILE *file = fopen(filename,"w");
if (file==NULL){
perror ("Error opening file");
printf("Error opening file\n");
}
else{
for (counter = 0; counter < number_of_lines; counter++)
{
fprintf(file, "%s\n",text_lines[counter]);
}
fclose(file);
}
pthread_mutex_unlock(&lock);
}