首页 > 解决方案 > 如何将数组存储在文件(数据库)中以及如何在程序中访问它

问题描述

在 C 中,如何将数组存储在文件(数据库)中以及如何在程序中访问它。在这个程序中,当我输入 ex.2 的索引号(包含 30)时,在我想将年龄减去 5 之后它显示 25 但是当我想更改索引号 2 时,它从 25 中减去,,,不是从给定的索引

#include<stdio.h>

#define PATH "/storage/emulated/0/c language/data2.txt"

int main()
{
    FILE *file;
    int age[] = {15,10,19,3}, s,i;
    printf("Enter the array index:");
    scanf("%d",&i);
    file = fopen(PATH, "r");
    if (file == NULL)
    {
        printf("files does not exist");
        return 1;
    }
    fscanf(file, "%d", &age[i]);
    fclose(file);
    printf("Enter how much age should to be subtracted:");
    scanf("%d", &s);

    file = fopen(PATH, "w");
    age[i] = age[i] - s;
    fprintf(file, "%d", age[i]);
    fclose(file);
    printf("%d", age[i]);
}

标签: carraysdatabasefilearraylist

解决方案


您必须将文件中的数据存储在数组中,对其进行编辑,然后将其加载回文件中。

fscanf(file, "%d", &age[i]);

此代码读取文件中的第一个整数并将其加载到 age[i]

fprintf(file, "%d", age[i]);

用 age[i] 替换文件的内容,之后你将得到一个只有 1 个数字的文件。


推荐阅读