c - store data from a file to a struct array -


i have spent lot of time last 2 day , stuck. cant understand how pointers , structs work function.

i pass array of type struct reference , parse file store values. used printf see did word in main values wrong. wonder if have use pointer pointer make work.

here function

int parse_sightings(char *file, struct sightings_data *recs) {     file *fptr;     char buf[50];     int lines=0;      fptr = fopen(file, "r");     if (fptr == null) {         ferror(fptr);         exit(1);     } else {          while (!feof(fptr)) {             char ch = fgetc(fptr);             if (ch == '\n') {                 lines++;             }         }         printf("%d\n",lines);     rewind(fptr);     recs = malloc(lines * sizeof (struct sightings_data));     int index = 0;     ///aber/dap/cetaceans/data/sightings_1.txt     while (!feof(fptr)) {         fscanf(fptr, "%s %c %lf %lf", &(recs + index)->id, &(recs + index)->type, &(recs + index)->lat, &(recs + index)->lon);         index++;      } }     fclose(fptr); int x;  (x = 0; x < lines; x++) {     printf("%s %c %.2f %.2f\n", (recs + x)->id, (recs + x)->type, (recs + x)->lat, (recs + x)->lon); } return lines; } 

the printf gives correct output. problem appeals in in main

in main: declare struct here

struct sightings_data sight_recs[]; 

here function

lines_sights=parse_sightings(file_2,&sight_recs); 

and check array

for(i=0;i<lines_sights;i++){     printf("%s %c %.2f %.2f\n", (sight_recs + i)->id, (sight_recs + i)->type, (sight_recs + i)->lat, (sight_recs + i)->lon); } 

i couldnt find or example example clear. basic , thinks have become confusing afterward. debugger inform me lat, type, lon , id out of range. how first prints data?

i know doing wrong, best approach , resource learn more structs in memory, how allocate it, how parse etc.

i cant understand issue feof(). rewind() returns pointer beginning of file. right? why feof cant indicate end of file?

feof() can indicate end of file, after end of file has been encountered, is, after has been attempted read past end. so, loop

    while (!feof(fptr)) {         fscanf(fptr, "%s %c %lf %lf", &(recs + index)->id, &(recs + index)->type, &(recs + index)->lat, &(recs + index)->lon);         index++;         // try printf("index = %d\n", index); here!     } 

will, after last line's data has been read, not yet have bumped end-of-file, , iterate loop 1 more time. might not issue here, such usage of feof() can lead errors if 1 isn't aware of implications.


Comments

Popular posts from this blog

javascript - Wordpress slider, not displayed 100% width -

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -