Vida Ras
Vida Ras

Reputation: 1

C: How can I read a huge amount integers of a file into a huge enough array?

I'm writing a program to read csv files containing only ints. The problem I'm facing is some of the files contain about 1000000 different numbers and thus an array is too small to store all the numbers. The code I have written reads the file successfully but does not store the correct integers and only repeats one number. Can someone please help me correct my mistake that would be greatly appreciated.

FILE *file;
file = fopen(filename, "r");

int *list;
int count = 0;                // count the numbers in the file 

printf("\t- Readed %d numbers\n", count);

list = ( int* ) malloc( count * sizeof(int) );       // create momary 

if( !(list = ( int* ) malloc( count * sizeof(int) )))
{
    printf("\tMemory allocation failed\n\n");
}
else
{
    printf("\tMemory allocation suceeded\n\n");
}

// scanning content into array

int i;
for( i = 0; i < count; i++ )
{
    fscanf( file, "%d,", &list[i] );
    printf( "%d\n", list[i] );
}

Upvotes: 0

Views: 49

Answers (1)

chux
chux

Reputation: 153498

Various troubles

Allocation for only 0 int @Michael Dorgan

// int count = 0;
#define N  1000000
int count = N;

Wrong null test

OP is allocating again, losing access to the first allocation.

// if( !(list = ( int* ) malloc( count * sizeof(int) )))
if (list == NULL)

No fscanf() check

// fscanf( file, "%d,", &list[i] );
if (fscanf( file, "%d,", &list[i] ) != 1) break;

Clean-up

// add after the loop
fclose(file);

Other

Simplify code

// list = ( int* ) malloc( count * sizeof(int) );       // create momary 
list = malloc(sizeof *list * count);

Debug

Add a print to find how much was read.

// after the loop
printf("i: %d\n", i);

Upvotes: 0

Related Questions