Storing values from a file into array of structs
Hey everyone, I'm trying to store some information about different employees (from a text file 'payfile') into an array of structs. I wrote out some code and it seems to be working, but whenever I try outputting it, it prints more than what should theoretically be stored in each member of the struct.
In the code below, the printf functions were just used to see if it was storing the information correctly...can you find anything wrong?
EDIT: I'm guessing it has something to do with initializing the buf and temp arrays...
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX 100
struct employee {
char first[7];
char initial[1];
char last[9];
char street[16];
char city[11];
char state[2];
char zip[5];
int age;
char sex[1];
int tenure;
float salary;
} workers[MAX];
char* strsub(char *buf, char *s, int start, int end) {
int i, j;
for (j=0, i=start; i<=end; i++, j++)
s[j] = buf[i];
s[j] = '\0';
return s;
}
main (void)
{
FILE *payfile;
FILE *csis;
char buf[MAX] = {0};
char temp[MAX] = {0};
int i = 0;
csis = fopen("csis.txt", "w");
payfile = fopen("payfile.txt", "r");
if (payfile == NULL){
printf("Error: Could not open file");
exit(EXIT_FAILURE);
}
while (!feof(payfile)) {
fgets(buf, MAX, payfile);
strsub(buf, workers[i].first, 0, 6);
strsub(buf, workers[i].initial, 8, 8);
strsub(buf, workers[i].last, 10, 18);
strsub(buf, workers[i].street, 20, 35);
strsub(buf, workers[i].city, 37, 47);
strsub(buf, workers[i].state, 49, 50);
strsub(buf, workers[i].zip, 52, 56);
strsub(buf, temp, 58, 59);
workers[i].age = atoi(temp);
strsub(buf, workers[i].sex, 61, 61);
strsub(buf, temp, 63, 63);
workers[i].tenure = atoi(temp);
strsub(buf, temp, 65, 70);
workers[i].salary = atof(temp);
++i;
}
printf("%s", workers[0].first);
printf("%s", workers[0].initial);
printf("%s", workers[0].last);
printf("%s", workers[0].street);
printf("%s", workers[0].city);
printf("%s", workers[0].state);
printf("%s", workers[0].zip);
printf("%d", workers[0].age);
printf("%s", workers[0].sex);
printf("%d", workers[0].tenure);
printf("%f", workers[0].salary);
getchar();
fclose(payfile);
fclose(csis);
return 0;
}
Thanks a lot for any help!