C 读取格式良好的文本文件
给定以下名为input.txt的格式良好的文本文件:C 读取格式良好的文本文件,c,malloc,scanf,realloc,C,Malloc,Scanf,Realloc,给定以下名为input.txt的格式良好的文本文件: Yesterday snowed Today is hot Tomorrow will rain Next week will earthquake 如果我不知道每个英语单词的长度,因为我不想在一个短单词上浪费1000字节,那么我如何逐行读取文本文件,并将内存作为字符数组动态分配给每个英语单词。在这种情况下应该使用realloc吗?以下是我的代码: int main() { FILE* pfile = fope
Yesterday snowed
Today is hot
Tomorrow will rain
Next week will earthquake
如果我不知道每个英语单词的长度,因为我不想在一个短单词上浪费1000字节,那么我如何逐行读取文本文件,并将内存作为字符数组动态分配给每个英语单词。在这种情况下应该使用realloc吗?以下是我的代码:
int main() {
FILE* pfile = fopen("input.txt", "r");
int i = 0;
while (i != 0) {
char* stringLiteral = (char*) malloc(1000 * sizeof(char));
i = fscanf(pfile, "%s", stringLiteral);
insertString(stringLiteral);
}
fclose("input.txt");
return 1;
}
void insertString(char* charArray) {
/*This function inserts a char array to a linked list*/
}
如果您愿意,您可以使用
realloc
,是的,在这种情况下,您需要重新分配更小的内存
您甚至可以通过char
在填充字符串时拉伸字符串来重新分配char
,而不浪费一个字节
带注释的示例:
#包括
#包括
int main(){
FILE*pfile=fopen(“input.txt”、“r”);
如果(pfile==NULL){//请检查打开文件时是否有错误
佩罗尔(“福彭”);
}
否则{
INTC;
int i=0;//字符串迭代器
char*stringLiteral;
stringLiteral=malloc(1);//初始分配
if(stringLiteral==NULL){
佩罗尔(“马洛克”);
返回退出失败;
}
而((c=fgetc(pfile))!=EOF){//,直到到达文件末尾为止
如果(c!='\n'){//直到行结束
stringLiteral=realloc(stringLiteral,i+1);//为每个字符重新分配内存
如果(stringLiteral==NULL){
佩罗尔(“马洛克”);
返回退出失败;
}
stringLiteral[i]=c;//将读取的字符分配给字符数组
i++;
}
否则{/'\n'已到达
stringLiteral[i]='\0';//终止字符串
//insertString(stringLiteral);//插入函数
printf(“%s\n”,stringLiteral);//测试打印
i=0;
}
}
//insertString(stringLiteral);//最后读取的行
printf(“%s\n”,stringLiteral);//测试打印
fclose(pfile);
}
返回退出成功;
}
这里的问题是,内存分配是一个昂贵的过程,可能会降低程序的速度
你必须权衡什么更重要,空间还是速度。除非字符串太大,无法放入堆栈中,否则在这种情况下,内存分配是一种方法,尽管分配字节块比逐字节分配更明智。您不能动态分配mrmory“作为字符串文本”*您是否尝试过一种简单的算法:1。读一个字符。2.那个角色是新词吗?3.如果没有,请分配更多空间并将其放入缓冲区。4.如果是新词,那么就不要再读了。@KamilCuk one realloc比fundy更有效:)@P_uj_u抱歉,我的错。它应该是一个字符数组,有效的方法是使用一个固定大小的输入缓冲区<代码>字符缓冲区[1024]代码>(根据正在读取的数据类型,选择合理的大小)。然后,您可以动态分配必要的内存,而无需重新分配。
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *pfile = fopen("input.txt", "r");
if (pfile == NULL) { //check for errors in opening file
perror("fopen");
}
else {
int c;
int i = 0; //string iterator
char *stringLiteral;
stringLiteral = malloc(1); //initial allocation
if(stringLiteral == NULL) {
perror("malloc");
return EXIT_FAILURE;
}
while ((c = fgetc(pfile)) != EOF) { //until the end of the file is reached
if (c != '\n') { //until the line ends
stringLiteral = realloc(stringLiteral, i + 1); //keep reallocating memory for each character
if(stringLiteral == NULL){
perror("malloc");
return EXIT_FAILURE;
}
stringLiteral[i] = c; //assing the read character to the char array
i++;
}
else { //'\n' was reached
stringLiteral[i] = '\0'; //terminate string
//insertString(stringLiteral); //your insertion function
printf("%s\n", stringLiteral); //test print
i = 0;
}
}
//insertString(stringLiteral); //last read line
printf("%s\n", stringLiteral); // test print
fclose(pfile);
}
return EXIT_SUCCESS;
}