c - 如何将文件的内容存储到数组中(直到其最大容量)
问题描述
在我的文件functions.c
中,我一直试图将*.txt
文件的内容存储到一个数组中。它确实有效。但是,它应该只存储它的大小。例如,如果数组大小为 5,则它只能存储 5 条记录,而忽略其余的。
file.txt
:
34
firstname
46
secondname
78
thirdname
avatar.h
:
struct avatar
{
int score;
char name[25];
};
functions.h
:
#include "avatar.h"
int readfile( struct avatar [], int*, char [ ] )
functions.c
:
#include <stdio.h>
#include "functions.h"
int readfile(struct pokemon avatararray[], int * i, char filename[]) {
FILE * fp;
struct avatar rd;
fp = fopen(filename, "r");
if (fp == NULL) {
return -1;
}
while (fscanf(fp, "%d ", & rd.score) != EOF) {
avatararray[ * i] = read;
* i += 1;
}
}
return *i;
}
main.c
:
#include <stdio.h>
#include "functions.h"
int main(int argc, char * argv[]) {
struct avatar avatarbank[5];
int numavatars;
char filename[] = "somefile.txt";
readfile(avatarbank, &numavatars, filename)
}
解决方案
你可能想要这样的东西:
// Read avatars froma file into an array
// avatararray : pointer to array
// arraysize : maximum size of array
// filename : filename to read from
// return value : number of avatars read, -1 if file could not be opened
//
int readfile(struct pokemon avatararray[], int arraysize, char filename[]) {
int itemsread = 0;
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
return -1;
} else {
struct avatar rd;
while (arraysize-- >= 0 && fscanf(fp, "%d %s", & rd.level, rd.name) != EOF) {
avatararray[itemsread++] = rd;
}
}
fclose(fp); // don't forget to close the file
return itemsread;
}
#define ARRAYSIZE 5
int main(int argc, char * argv[]) {
struct avatar avatarbank[ARRAYSIZE];
char filename[] = "file.txt";
int itemsread = readfile(avatarbank, ARRAYSIZE, filename);
if (itemsread != -1)
{
printf("Read %d items\n", itemsread);
}
else
{
printf("Could not read items\n");
}
}
免责声明:这是未经测试的代码,甚至可能无法编译,但您应该明白这一点。
推荐阅读
- javascript - CKEditor5 自定义模态插件
- angular - 指定的模块不存在Angular 6
- c# - WinForms,.NET - 在编译程序中读取设置文件
- django - Django Updateview - 根据字段值或用户对象设置参数
- c# - 从有效对象到位图的转换导致 null c#
- oracle - 使用 groovy:更新时间戳 oracle 列
- stanford-nlp - Using POS Taggers will raise wrong format in German
- java - Apache servicemix OSGi 包无法导入包
- php - 如何设置 PHP 类 VISIBLITY
- c# - 文本框为空时如何防止数据提交到数据库