给定以下格式正确的文本文件,称为input.txt:
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
拉伸字符串来重新分配,而不浪费单个字节。
带有注释的示例:
#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;
}
这里的问题是内存分配是一个昂贵的过程,并且会降低程序速度。
您必须权衡更重要的空间或速度。除非字符串太大而不能容纳在堆栈中,否则在这种情况下,内存分配是必经之路,尽管分配字节块而不是逐字节分配更为明智。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句