Monday, 15 August 2011

c - Why isn't my loop reaching the end of the file? -



c - Why isn't my loop reaching the end of the file? -

i building application in visual studio 2012 on windows 8.1 uses linear regression calculate/predict world population @ year in time. info beingness read in text file , programme uses info calculate linear regression.

text file contents:

0.001 0.200 1.000 0.310 1.500 0.450 1.650 0.500 1.750 0.791 1.800 0.978 1.850 1.262 1.900 1.650 1.927 2.000 1.950 2.519 1.955 2.756 1.960 2.982 1.965 3.335 1.970 3.692 1.975 4.068 1.980 4.435 1.985 4.831 1.990 5.263 1.995 5.674 2.000 6.070 2.005 6.454 2.008 6.707 2.009 6.800

the issue having when loop through file store info in array of structs, exception before can read file.

this function i'm having issues with:

int readfile(char* filename) { char line[20]; int = 0; int recordcount = 0; file* file = null; population* wp[] = {0}; file = fopen(filename, "r"); /* open text file reading */ if (file != null) { printf("file opened reading\n"); while (fgets(line, 20, file) != null) { fscanf(file, "%s", line); recordcount++; } fclose(file); printf("there %d records.\n\n", recordcount); //*wp = (population*)malloc(sizeof(population) * recordcount); file = fopen(filename, "r"); (i = 0; < recordcount; i++) { wp[i] = (population*)malloc(sizeof(population)); fscanf(file, "%5f", &wp[i]->year); printf("%f ", wp[i]->year); fscanf(file, "%5f", &wp[i]->population); printf("%f\n", wp[i]->population); } } fclose(file); homecoming 1; }

the final loop (the 1 malloc space struct) 1 crashes program. can 3 iterations before crashes on 4th one.

exception thrown:

first-chance exception @ 0x7741d7e0 (ntdll.dll) in worldpopulation.exe: 0xc0000005: access violation reading location 0x871eadd7. unhandled exception @ 0x7741d7e0 (ntdll.dll) in worldpopulation.exe: 0xc0000005: access violation reading location 0x871eadd7.

the exception seems caused file pointer becoming corrupted, have no thought why. can help me figure out why lastly loop causes crash? thanks!

while (fgets(line, 20, file) != null) { fscanf(file, "%s", line); recordcount++;

you reading twice , counting once. first using fgets , using fscanf. guessing want rid of fscanf.

an additional problem is:

population* wp[] = {0}; [...] wp[i] = (population*)malloc(sizeof(population));

it illegal access other wp[0]. again, guessing want allocate like:

population** wp = malloc(recordcount * sizeof *wp);

the way reading file twice not efficient. should fscanfs first time around , grow wp needed realloc.

c loops visual-studio-2012 file-io struct

No comments:

Post a Comment