【发布时间】: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