【发布时间】:2012-07-05 02:55:27
【问题描述】:
我有如下所示的输入文件
5
8
10
实际上我需要在上面的示例中读取文件更多行。(中间没有空格。因此,我需要让数组的大小取决于文本文件的行。这是我使用的方法通过发生 r
#include "stdafx.h"
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int _tmain(int argc, _TCHAR* argv[])
{
FILE *test;
int numbers[]={0};
int i=0;
char *array1;
if((test=fopen("Input1.txt","r"))==NULL)
{
printf("File could not be opened\n");
}
else
{
array1 = (char*)malloc(1000*sizeof (char));
if((test=fopen("Input1.txt","r"))==NULL)
{
printf("File could not be opened\n");
}
else
{
while(fgets(array1,(sizeof array1)-1,test)!=NULL)
{
numbers[i]=atoi(array1);
i++;
}
for(i=0;i<sizeof(array1)-1;i++)
{
printf("%d\n",numbers[i]);
}
}
fclose (test);
}
system("pause");
return 0;
free(array1);
}
【问题讨论】:
-
您在
numbers的定义中缺少元素计数(例如numbers[1000])。 -
但我需要它随文本大小而变化。如果文本大小大于我所拥有的,那么我也会面临错误
-
@user15020809 好的,所以...动态分配它。如果需要,以某个固定长度开始。您以后可以随时使用
realloc对其进行扩展。 -
如何使用 realloc 来扩展它??在这种情况下?
-
realloc的文档在这里:cplusplus.com/reference/clibrary/cstdlib/realloc
标签: c error-handling runtime-error