【问题标题】:Check if file exist in C. If so continue read the last value of the file and increment by one检查 C 中是否存在文件。如果存在,则继续读取文件的最后一个值并加一
【发布时间】:2026-01-04 15:10:02
【问题描述】:

即使我删除了“file.txt”,程序仍然会进入if语句。

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

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
}

【问题讨论】:

  • 你的第一个 if 语句没有意义,因为你的变量在 decalre 时没有默认为 null。如果您将第一行设置为 myFile = null 那么您的代码将起作用。你拥有它的方式意味着它是用未定义的值初始化的。

标签: c printf scanf fopen file-exists


【解决方案1】:

首先尝试打开文件进行阅读。如果这不起作用(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);

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

【讨论】:

  • 谢谢我实现了。但是如何读取存储在文件中的 BookId 的最后一个值,然后使用 for 循环将其加一?
  • 您必须解析您的文件以计算出该信息。