gpt4 book ai didi

检查C中是否存在文件。如果存在,则继续读取文件的最后一个值并加一

转载 作者:行者123 更新时间:2023-11-30 20:03:33 24 4
gpt4 key购买 nike

即使我删除了“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
}

最佳答案

首先尝试打开文件进行读取。如果这不起作用(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中是否存在文件。如果存在,则继续读取文件的最后一个值并加一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49349319/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com