C 如何将文件内容存储到数组中(直到其最大容量)
在我的文件C 如何将文件内容存储到数组中(直到其最大容量),c,C,在我的文件functions.c中,我一直试图将*.txt文件的内容存储到一个数组中。它确实有效。但是,它应该只存储其大小。例如,如果数组大小为5,则它只能存储5条记录,而忽略其余记录 file.txt: 34 firstname 46 secondname 78 thirdname avatar.h: struct avatar { int score; char name[25]; }; #include &quo
functions.c
中,我一直试图将*.txt
文件的内容存储到一个数组中。它确实有效。但是,它应该只存储其大小。例如,如果数组大小为5,则它只能存储5条记录,而忽略其余记录
file.txt
:
34
firstname
46
secondname
78
thirdname
avatar.h
:
struct avatar
{
int score;
char name[25];
};
#include "avatar.h"
int readfile( struct avatar [], int*, char [ ] )
函数.h
:
struct avatar
{
int score;
char name[25];
};
#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;
}
#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");
}
}
免责声明:这是未经测试的代码,甚至可能无法编译,但您应该明白。
int-numavatars
-hmm您认为numavatars
最初的价值是什么?提示:它没有初始值,因为您从未提供过。将数组大小作为参数传递给readfile
函数,并在达到其大小后停止读取。唯一的问题是我无法将函数的参数从指针更改为int@JoanaF. 没问题,你应该可以改变,这只是一个小小的改变。您还应该添加问题中提供给您的readfile
的完整规范。你可以回答你的问题