c - 如何检测文件中是否存在数据 C 文件处理

标签 c file file-handling

我对 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/

相关文章:

python - 在Python中读取具有大量列的文件

android - 如何将现有的仅 header 源文件添加到 android studio?

python - 如何摆脱数组中的内置引用并将其保存到文件中

c - 如何拦截编辑框中的粘贴事件?

c - 如何知道引用的 fp 当前正在写入哪个文件?

c# - 系统.IO.IOException : The process cannot access the file '.txt' because it is being used by another process

javascript - 文件处理 typescript Angular 2 的基本语法

java - FileInputStream 读取的文件存储在哪里?

C 中不区分大小写的字符串比较

c - 如何使用 snprint() 函数追加字符串