【发布时间】:2020-11-07 23:17:29
【问题描述】:
我正在学习C,我需要读取一个文本文件,但我只能使用“write,malloc,free,open,read,close”。
这是我的代码:
#define MAXCHAR 10000
int open_fp(int check)
{
char *int_vector;
int fp,len;
int i,j;
char buffer[MAXCHAR];
if(check == 0) //standard list
{
if((fp = open("file.txt", O_RDONLY)) != -1) //check if the fp is opened. -1 = error
{
printf("\n%d\n",fp); // DEBUG FUNCTION
sleep(1);
if (!(int_vector = (char*)malloc(sizeof(char) * sizeof(char))))
{
printf("\nWrong allocation\n!"); // DEBUG FUNCTION
return(0);
}
len = read(fp,int_vector,MAXCHAR);
for(i=0;i<len;i++)
{
printf("%c",int_vector[i]);
}
}
else
{
printf("File error!");
return (0);
}
}
return(0);
}
现在我的问题是:如您所见,
char buffer[MAXCHAR];
我已经创建了静态缓冲区,但我想创建一个动态缓冲区,它允许我根据文本文件中的字符数调整缓冲区的大小,但我不知道如何......有人有诡计???????? ?
【问题讨论】:
-
您可以使用
malloc()分配并使用realloc()调整大小。如果您“不允许”使用realloc(),那么您可以分配另一个大小合适的缓冲区,复制数据,然后free()第一个缓冲区。 -
...或者您可以从一个小的(比如 1024 字节)缓冲区开始,并继续读取和重新分配,直到文件被读取。然后你最多有 1023 个字节未使用。
-
@Weather Vane 谢谢你的回复!不幸的是我不能使用 realloc 功能!还是谢谢你的回复!!
-
我提到了你可以做的事情。
-
@WeatherVane 是的,我现在看到了!