As i said in the title. This is how my program starts: I call this function to create a file (if it doesn't previously exist), and if it does exist it will take the info in the file and stock them into a struct, that i created. You will find the code below.
But here is the part that still i can't found solution to, if i delete all the files and launch the program, the file will be created, i go simultaneously to the folder and i can delete them by myself with no problem (the program still working in the background).
SO the issue is not
in the first IF
where the file got closed.
But when i launch the program again with the file already exists (so the program will go for the ELSE IF
and collect the data ) here starts the problem, when i launch the program and simultaneously go to the folder to try and delete the file manually an error msg pop up and tell me that the file is being opened in a program (the program still working in the background). Despite that i'm using the the fclose(fc).
So where is the problem in my script? i really spent days trying to solve this problem. and i need to solve because next in my program i need to be able to remove the file (so i can name another one with his name) here is the script
int file_fc(classe c[])
{
FILE * fc;
int count=0;
char buffer[500];
if ((fc=fopen("Fclasse.txt","r"))==NULL)
{
fc=fopen("Fclasse.txt","w");
fprintf(fc,"Code Classe Libellé Classe Spécialite Capacité\n");
fclose(fc);
fclose(fc);
}
else
{
fc=fopen("Fclasse.txt","r");
{
fgets(buffer,300, fc);
fgets(buffer,300, fc);
while(feof(fc) == 0)
{
sscanf(buffer,"%11d %16s %16s %5d",&c[count].code, c[count].lib, c[count].spec, &c[count].capa);
count++;
fgets(buffer,300, fc);
}
}
fclose(fc);
}
return (count);
ediiit::: changed the script to this
fc=fopen("Fclasse.txt","r");
if (fc==NULL)
{
fc=fopen("Fclasse.txt","w");
fprintf(fc,"Code Classe Libellé Classe Spécialite Capacité\n");
fclose(fc);
}
else
{
fgets(buffer,300, fc);
fgets(buffer,300, fc);
while(feof(fc) == 0)
{
sscanf(buffer,"%11d %16s %16s %5d",&c[count].code, c[count].lib, c[count].spec, &c[count].capa);
count++;
fgets(buffer,300, fc);
}
}
fclose(fc);
and it's working perfectly. what i still don't understand if i do this as i was doing before
if(fc=fopen("fclasse.txt","r")==NULL)
where am i supposed to put the fclose()? inside the if? at the end of the function ??
Or simply do i need to count how many times i opened the file and at the end before closing the file, i write Fclose() as many time as i opened (i mean the place where i put fclose doesn't matter) ??
You open the file three times, throwing away two of the opened objects. Then you only close once. The two others stay open until the program closes.
You open it first time in the if
, then you open it again in else if
and then third time inside the block. Only the first one should be there.