-2

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
}
Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Klayd Pro
  • 1
  • 1
  • 2
  • 7
  • Your first if statement makes no sense because your variable isn’t defaulted to null when you decalre it. If you set the first line as myFile = null then your code would work. The way you have it means it is initialised with undefined value. – Andrew Truckle Mar 18 '18 at 19:30

1 Answers1

3

Begin by trying to open the file for reading. If that doesn't work (fopen returns NULL) then you try to open for writing. And if that doesn't work either, you bail.

With your code:

FILE *myFile = fopen("file.txt", "r+");

if (myFile != NULL)
{
    // File exists and is now open for reading and writing...
}
else
{
    myFile = fopen("file.txt", "w");
    if (myFile == NULL)
    {
        // Report error and handle it appropriately
    }

    // The file didn't exist, now it is created so we can write to it
}

// All done with the file
fclose(myFile);

I recommend you consider using functions for common code.

Andrew Truckle
  • 17,769
  • 16
  • 66
  • 164
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621