c - 读取格式良好的文本文件
问题描述
鉴于下面名为 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;
}
这里的问题是内存分配是一个昂贵的过程,并且会减慢您的程序。
你必须权衡什么更重要,空间或速度。除非字符串太大以至于无法放入堆栈,否则在这种情况下内存分配是可行的方法,尽管分配字节块而不是逐字节分配可能更明智。
推荐阅读
- reactjs - 在 Apollo 中提交表单后,如何从 useQuery 挂钩中获取数据?
- excel - 用下划线替换两个单词之间的空格
- python - 通过 pytorch 中的张量切片,火炬分配不到位
- azure-functions - 如何排队从 blob 触发器收到的请求?
- html - 如何使用 flexbox 垂直对齐具有相同高度但身体部分灵活的卡片内的页脚
- windows - 消息 156,级别 15,状态 1,第 20 行关键字“或”附近的语法不正确
- certificate - 如何找出数字证书有什么问题?
- python - Tensorflow LSTM:如何为每批使用不同的权重?
- azure - 在 Grafana 中监控 Azure API 管理响应时间
- pandas - 拟合时的简单模型错误:发现样本数量不一致的输入变量