2016-01-28 59 views
-3

我有一个包含一组数字的文件。 我试图将这些数字读入数组中。我使用一个指针为该数组分配内存,并从该文件读入该位置。 由于某些原因,程序不会从文件中读取超过5个值。整个文件没有读取

int main(int argc, char* argv[]) 
{ 
    int i=0, count=0; 
    //unsigned long int num[1000]; 
    unsigned long int *ptr; 
    ptr = (unsigned long int*) malloc (sizeof(unsigned long int)); 
    char file1[30], file2[30]; 
    int bin[1000][32]; 
    int ch; 

    argv++; 
    strcpy(file1,*argv); 

    FILE *fp; 
    fp=fopen(file1, "r"); 

    while((fscanf(fp,"%ld",ptr))==1) 
    { 
     ptr++; 
     count++; 
    } 

    ptr=ptr-count; 
    for(i=0; i<count;i++,ptr++) 
     printf("%ld\n",*ptr); 
    return 0; 
} 

输入文件包含以下内容:

1206215586 
3241580200 
3270055958 
2720116784 
3423335924 
1851806274 
204254658 
2047265792 
19088743 

输出仅仅是这样的:提前

1206215586 
3241580200 
3270055958 
2720116784 
3423335924 

感谢。

+5

您尝试读取多个值到内存中只有一个值足够大。 – usr2564301

回答

2

您需要分配足够的空间来存储整数。要这样做,请使用原始指针上的realloc函数。

您编写ptr++的事实使得在原始指针上调用realloc并保存结果变得很尴尬。所以最好不要使用ptr++。相反,您可以使用ptr[count]并将ptr始终指向分配的开始。

例如主循环可能是:

while((fscanf(fp,"%lu",&ptr[count]))==1) 
{ 
    count++; 

    void *new = realloc(ptr, (count+1) * sizeof(*ptr)); 
    if (!new) 
     break;  // maybe print error message, etc. 

    ptr = new;   
} 

// don't do this any more 
//  ptr=ptr-count; 
+0

注意:'void * new = ...'是确保这些代码不会用C++编译的一种方法。 ;-) – chux

+0

非常感谢。 :) – Aravind