Even if I delete the " file.txt " the program still enters the if
statement.
What I want to achieve is to check if there is a file with that name. If so then read the last value of BookId
and increment it by one with for
loop:
FILE *myFile;
if (myFile==NULL) // if the file doesn't exists
{
myFile=fopen("file.txt","w"); // Fresh write
fprintf(myFile, "%s\t%s\t%s\t\n\n",Book_Id,Record_Date,Book_Name); // Column name (id, date, name)
//writing the values
for (x=0;x<NR_OF_BOOKS; x++)
{
fprintf(myFile, "%03d\t",BookId++);
fprintf(myFile, "%02d/%02d/%04d\t",dd[x],mm[x],yy[x]);
fprintf(myFile, "%s\n",Bookname[x]);
}
}
else // file exists
{
//reading
myFile=fopen("file.txt","r"); //open in read mode
fscanf(myFile,"%03d,",&BookId); // I want to read the last value of BookId
myFile=fopen("file.txt","a"); // I open in append mode to add BookId++
for (x=0;x<NR_OF_BOOKS; x++)
{
fprintf(myFile, "%03d\t",BookId++); // here continues to count the BookId
fprintf(myFile, "%02d/%02d/%04d\t",dd[x],mm[x],yy[x]); // date
fprintf(myFile, "%s\n",Bookname[x]);// book name
}
}
fclose(myFile); // closing the file
}