eastboundr
eastboundr

Reputation: 1877

How to store a big set of data into an array in C

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);
    }
}

Upvotes: 0

Views: 464

Answers (3)

eastboundr
eastboundr

Reputation: 1877

The array can be established and stored. However using malloc does make more sense. Thanks all.

Upvotes: 0

Morpfh
Morpfh

Reputation: 4093

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.


Upvotes: 1

Tarion
Tarion

Reputation: 17134

You have written:

while (k!=80000)

Might be the reason to stop at 80.000

Upvotes: 0

Related Questions