【发布时间】:2019-01-31 05:58:25
【问题描述】:
我对 C 中的文件处理非常陌生。我想问一下是否有任何方法可以检测文件上是否存在现有数据。因为如果没有,我将使用"wb",但如果已经有数据,我将使用附加"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();
}
【问题讨论】:
-
你真正的问题是什么。你失败的代码是什么?如果您提供的细节不佳,我们只能提供通用的解决方案。如果您可以读取除第一组数据之外的所有内容,那么这可能是您的代码中的错误,您没有向我们显示。
-
你写完后验证你的文件内容了吗?你怎么能确定你的问题是写入文件而不是读取?
-
我添加了我的程序示例。
-
递归调用
showOptions会吃掉你的堆栈。 -
在检查
NULL之前,您还可以使用fp。
标签: c file file-handling