I'm sure it's my lack of coding skills, not fread's fault : ).
I'm trying to read a text file full of integers into an array. The input file consists of one integer per line and the number of lines will be dynamic in the program.
Input example:
1
2
3
etc...
If I take out the fread error check thing (!=elements etc.) I get an array full of zeros. As it stands now, all I get is "error reading file". Any ideas are most welcome!Code:long lSize; char filename[25]; char temp[50]; FILE *pfile; int elements; int *realdata; int count; //get file name, open file printf("\n\n\tEnter file name with path:"); scanf("%s",filename); printf("\n\tFile: %s",filename); pfile = fopen (filename,"r"); if (pfile==NULL) { perror("\tFile open error"); exit(EXIT_FAILURE); } else // obtain file size: fseek (pfile , 0 , SEEK_END); lSize = ftell (pfile); rewind (pfile); printf("\n\tFile size: %ld bytes",lSize); //count lines for dynamic allocation of array while ( fgets ( temp, sizeof temp, pfile) != NULL ) { elements++; } printf("\n\tNumber of elements: %d",elements); printf("\n\tElement size: %ld\n\n",sizeof(int)); //dynamic allocation of array for real data realdata=calloc(elements, sizeof(int)); if (realdata == NULL) { perror("\tReal Data array allocation error"); exit(EXIT_FAILURE); } else //read file data to real data array if (fread (realdata,sizeof(int),(size_t)elements,pfile)!=elements) { fprintf(stderr, "\terror reading file\n\n"); exit(1); } fclose(pfile); //print real data array for (count = 0; count < elements; count++) { printf("%d", realdata[count]); }
As a side note why do both ubuntu and ftell claim the size of a particular txt file is 330 bytes when 4bytes/integer x 149 integers = 596 bytes. Should my array be allocated for size of integers*number of integers, or the size yielded by ftell? TIA!!



LinkBack URL
About LinkBacks



