首页 > 解决方案 > 如何将文件的内容存储到数组中(直到其最大容量)

问题描述

在我的文件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) 
        }

标签: c

解决方案


你可能想要这样的东西:

// 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");
   } 
}

免责声明:这是未经测试的代码,甚至可能无法编译,但您应该明白这一点。


推荐阅读