Итак, я попытался написать функцию для загрузки данных из файла в массив структур, а одно из полей struct - это массив другого пораженного типа. Можно ли прочитать часть данных из одного файла (users.csv), а затем (loan.csv). На данный момент он дает мне «Невозможно открыть файл» (null) »
#define MaxUsers 1000
struct User {
char* register_name;
char* login; //unique for each
unsigned int status; // librarian (special user) has status 0, others have 1
unsigned int numberBorrowed;
struct Book books_borrowed[MaxBorrowed]; //array of books borrowed by the user
};
struct UserArray {
struct User* array; //pointer to an array of struct User
unsigned int length; //length of an array of struct User
};
struct Book {
char *title; //book title
char *authors; //comma separated list of authors
unsigned int year; // year of publication
unsigned int copies; //number of copies the library has
unsigned int status; //to tell whether it has been borrowed - 1 for borrowed, 0 if in library
};
struct User all_users[MaxUsers];
struct UserArray u_array = {&all_users[0], 0}; //hold pointer to all_users array and its length
int load_users(FILE* file)
{
char *field;
int i=0;
FILE* fb;
//open the CSV file
file = fopen("users.csv","r");
if(file == NULL)
{
printf("Unable to open file '%s'\n",file);
exit(1);
}
char characters[400];
// process the data
// the file contains 5 fields in a specific order:
// register_name, login, status, numberBorrowed, array of struct Book
// separated by commas
while(fgets(characters,400,file)) //need to write function getline() to jump to the next row while reading the cvs file* update - it works
{
//get register_name
field=strtok(characters,",");
all_users[i].register_name=malloc(strlen(field)+1);
strcpy(all_users[i].register_name, field);
// get login
field=strtok(NULL,",");
all_users[i].login=malloc(strlen(field)+1);
strcpy(all_users[i].login, field);
// get status
field=strtok(NULL,",");
all_users[i].status=atoi(field);
// get numberBorrowed
field=strtok(NULL,",");
all_users[i].numberBorrowed=atoi(field);
// get books
fb = fopen("loans.csv","r");
char* fieldB;
int j=0;
char book_chars[400];
while (fgets(book_chars, 400, fb) && j<all_users[i].numberBorrowed)
{
field=strtok(book_chars,",");
all_users[i].books_borrowed[j].title=malloc(strlen(field)+1);
strcpy(all_users[i].books_borrowed[j].title, field);
field=strtok(NULL,",");
all_users[i].login=malloc(strlen(field)+1);
strcpy(all_users[i].books_borrowed[j].authors, field);
field=strtok(NULL,",");
all_users[i].books_borrowed[j].year=atoi(field);
field=strtok(NULL,",");
all_users[i].books_borrowed[j].copies=atoi(field);
field=strtok(NULL,",");
all_users[i].books_borrowed[j].status=atoi(field);
j++;
}
i++;
}
u_array.length=i;
// close file
fclose(file);
return 0;
}