即使删除“ file.txt”,程序仍会输入if语句。

我要实现的是检查是否存在具有该名称的文件。如果是这样,则读取BookId的最后一个值,并通过for循环将其递增1:

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
}

最佳答案

首先尝试打开文件进行读取。如果这不起作用(fopen返回NULL),则尝试打开进行写入。如果那也不起作用,您就要保释。

使用您的代码:

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);




我建议您考虑将函数用于通用代码。

关于c - 检查文件是否存在于C中。如果是,则继续读取文件的最后一个值,并递增一个,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49349319/

10-14 19:19
查看更多