简体   繁体   English

C:如何将文件的大量整数读入足够大的数组?

[英]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.我正在编写一个程序来读取仅包含整数的 csv 文件。 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.我面临的问题是一些文件包含大约 1000000 个不同的数字,因此数组太小而无法存储所有数字。 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] );
}

Various troubles各种烦恼

Allocation for only 0 int @Michael Dorgan仅分配 0 int @Michael Dorgan

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

Wrong null test null测试错误

OP is allocating again, losing access to the first allocation. OP 再次分配,失去对第一个分配的访问权限。

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

No fscanf() check没有fscanf()检查

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM