Fred
Fred

Reputation: 240

How to store the contents of a file into an array (until its maximum capacity)

In my file functions.c I have been trying to store the contents of a *.txt file into an array. It does work. However, it should only store it to its size. For example, if the array is size 5, it can only store 5 records and ignore the rest.

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) 
        }

Upvotes: 2

Views: 110

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50775

You probably want something like this:

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

Disclaimer: this is untested code that may not even compile, but you should get the idea.

Upvotes: 2

Related Questions