我对 C 中的文件处理非常陌生。我想问一下是否有任何方法可以检测文件中是否存在现有数据。因为如果没有,我将使用 "wb"
,但如果已经有数据,我将只使用 append "ab"
。
当我写入数据时,我尝试使用 "wb"
而不是 "ab"
,但是我写入的第一个数据不会被读取。
这是一个例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct clientInfo{
char Name[30];
};
void inputAccounts();
void viewAllRecords();
int main()
{
showOptions();
}
void inputData()
{
FILE *fp;
fp = fopen("hello", "ab");
struct clientInfo PERSONAL;
if(fp == NULL)
{
printf("Error!!!");
getch();
}
else
{
fflush(stdin);
printf("Enter Name: ");
gets(PERSONAL.Name);
fwrite((char *)&PERSONAL, sizeof(struct clientInfo), 1, fp);
printf("File Created!!!");
getch();
fclose(fp);
}
}
void showOptions()
{
char choice;
system("cls");
printf("\n[1] Add Accounts");
printf("\n[2] View Records");
choice = getch();
if (choice == '1')
{
inputData();
}
else if (choice == '2')
{
viewAllRecords();
}
showOptions();
}
void viewAllRecords()
{
FILE *fp;
fp = fopen("hello", "rb");
struct clientInfo PERSONAL;
fread((char *)&PERSONAL, sizeof(struct clientInfo), 1, fp);
system("cls");
if(fp == NULL){
printf("Error!!!");
getch();
}
else
{
while((fread((char *)&PERSONAL, sizeof(struct clientInfo), 1, fp))==1)
{
printf("Name: %s\n", PERSONAL.Name);
}
}
getchar();
}
最佳答案
您可以使用 fseek()
来实现您的目的。 fseek()
用于将与给定文件关联的文件指针移动到特定位置。
FILE *fp;
fp = fopen("test.txt", "r");
// Moving pointer to end
fseek(fp, 0, SEEK_END);
if(ftell(fp)>0){
printf("data exists on the file.\n");
}else{
printf("no data.\n");
}
有关更多详细信息,您可以阅读 this文章。
关于c - 如何检测文件中是否存在数据 C 文件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54454215/