gpt4 book ai didi

c - 如何在文件(数据库)中存储数组以及如何在程序中访问它

转载 作者:行者123 更新时间:2023-11-30 19:25:31 25 4
gpt4 key购买 nike

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

最佳答案

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

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

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

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

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

关于c - 如何在文件(数据库)中存储数组以及如何在程序中访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58667912/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com