【问题标题】:How to store array in file(database) and how to access it in program如何将数组存储在文件(数据库)中以及如何在程序中访问它
【发布时间】:2019-11-02 03:01:44
【问题描述】:

在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]);
}

【问题讨论】:

    标签: c arrays database file arraylist


    【解决方案1】:

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

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

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 2013-02-04
      相关资源
      最近更新 更多