I have a data file named somedata.dat, it contains a list of number pairs. about 10000 pairs. Like this:
3 19
5 213
1 34
7 93
I try to open the file, and read them, then put the numbers in a 10000x2 array. However, with the following code, it stops running when the loop hits about the 80000th time (needless to say EOF). Any ideas? Thanks.
int main(int argc, char *argv[])
{
int data[10000][2];
FILE *fp;
char s[5];
char temp[2];
char cur;
char next;
int pid=0;
int k=0;
fp = fopen("c:\\somedata.dat","r");
while (!EOF)
{
cur = fgetc(fp);
if (cur==' ')
{
data[pid][0]=atoi(s);
memset(&s[0], 0, sizeof(s));
}
else if (cur=='\n')
{
data[pid][1]=atoi(s);
pid++;
memset(&s[0], 0, sizeof(s));
}
else
{
temp[0]=cur;
temp[1]='\0';
strcat(s,temp);
}
}
calloc
) to deal with large data sets - Basile Starynkevitch 2012-04-04 07:29
The array can be established and stored. However using malloc does make more sense. Thanks all.
Edit:
You define an array of 20,000 and try to add aprox 10,000 paris, and it stops at 80,000?
Would guess it is, since you have no break in the loop, it reads 10,000, then read EOF 70,000 times + do some strange stuff to the array. Then exits.
You have to compare EOF
to something.
Typically:
int c; /* Has to be int, not char */
while((c = fgetc(fh)) != EOF) {
...
}
Also; take a look at fscanf, from stdio.h. Perhaps better suited for your usage.
As well; fgetc()
retrieve one and one int representable as char or EOF.
I.e. File:
12 33
16 693
Then fgetc would retrieve:
1: '1'
2: '2'
3: ' '
4: '3'
5: '3'
6: '\n'
7: '1'
8: '6'
...
Further: Check when you use functions. If fgetc() return EOF, then you are either at EOF or a read error occurred. Check with feror etc.
feof(fh)
as a terminating condition of the loop - Basile Starynkevitch 2012-04-04 08:48
You have written:
while (k!=80000)
Might be the reason to stop at 80.000
while (k!=80000)
-- are you certain you didn't ask for it to stop working - sarnold 2012-04-04 07:29