Home > Software design >  Save file to struct
Save file to struct

Time:03-25

I need to read file and save it to struct.

EXAMPLE of file input:

Aaaaa Aaaaa 2010 999.00 999.00 999.00 999.00 999.00
Bbbbb Bbbbbbbb 2012 1001.00 1001.00 1001.00 1001.00 1001.00
Cccc Cccccccc 2010 1001.00 1001.00 1001.00 1001.00 1001.00

Code:

#include <stdio.h>
struct Worker {
  char name[20], surname[20];
  int year;
  double salary[5];
} arr[1000];
int number_of_workers = 0;
void load() {
  FILE *input = fopen("input.txt", "r");
  int i = 0, j;
  while (i < 1000) {
    fscanf(input, "%s %s %d\n", arr[i].name, arr[i].surname, arr[i].year);
    i  ;
    for (j = 0; j < 5; j  )
      fscanf(input, "%d ", arr[i].salary[j]);
    if (feof(input))
      break;
  }
  fclose(input);
  number_of_workers = i;
}
int main() {
  load();
  int i, j;
  for (i = 0; i < number_of_workers; i  ) {
    printf("%s %s %d ", arr[i].name, arr[i].surname, arr[i].year);
    for (j = 0; j < 5; j  )
      printf("%.2f ", arr[i].salary[j]);
    printf("\n");
  }
  return 0;
}

I get nothing on screen. Could you help me to fix this?

CodePudding user response:

Here is the fixed version.

You were missing & when reading ints and doubles. With fscanf you can just check for the number of items read to determine when you have reached the end of the file. Every line can be read in a single fscanf call (if you want to go that route), no need for double loops.

Edit: Just as a side note, with strings you have to be careful not to overflow the buffer. You could add s to limit the characters read. Also, you could check for the return value of fopen.

#include <stdio.h>

struct Worker {
  char name[20], surname[20];
  int year;
  double salary[5];
} arr[1000];

int number_of_workers = 0;

void load() 
{
    FILE *input = fopen("input.txt", "r");

    int i = 0;
    while ((fscanf(input, "%s %s %d %lf %lf %lf %lf %lf", arr[i].name, arr[i].surname, &arr[i].year, &arr[i].salary[0], &arr[i].salary[1], &arr[i].salary[2], &arr[i].salary[3], &arr[i].salary[4])) == 8 && i < 1000)
    {
        number_of_workers  ;
        i  ;
    }  
    fclose(input);
}
int main() 
{
    load();
    for (int i = 0; i < number_of_workers; i  ) 
    {
        printf("%s %s %d %.2f %.2f %.2f %.2f %.2f", arr[i].name, arr[i].surname, arr[i].year, arr[i].salary[0], arr[i].salary[1], arr[i].salary[2], arr[i].salary[3], arr[i].salary[4]);
        printf("\n");
    }
    return 0;
}
  • Related