c - 如何将数组存储在文件(数据库)中以及如何在程序中访问它
问题描述
在 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 个数字的文件。
推荐阅读
- node.js - 客户端不会在 socketio 中发出事件
- spring - TomcatServer 在 100 个并发请求后挂起
- c++ - 矩阵形成中的奇怪行为(C++,犰狳)
- flutter - Flutter 中 Dismissible 中的 PageView 无法正常工作
- jquery - Mysql全外连接两个子查询
- python - UnboundLocalError:分配之前引用的局部变量“余额”(Python)
- c# - Unity Physics.Raycast 在应该检测到对象时未检测到
- javascript - 如何让我的消息正确显示?
- java - 由于“包 javafx.collections 不存在”错误,Maven 无法编译
- python - 在 Colab 中同时运行多个单元