首页 > 解决方案 > 读取格式良好的文本文件

问题描述

鉴于下面名为 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*/
    }

标签: cmallocscanfrealloc

解决方案


如果你愿意,你可以使用realloc,是的,在这种情况下,你需要重新分配更小的内存。

您甚至可以通过在填充字符串时拉伸字符串来重新分配charchar而不会浪费一个字节。

带注释的示例:

现场演示

#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;
}

这里的问题是内存分配是一个昂贵的过程,并且会减慢您的程序。

你必须权衡什么更重要,空间或速度。除非字符串太大以至于无法放入堆栈,否则在这种情况下内存分配是可行的方法,尽管分配字节块而不是逐字节分配可能更明智。


推荐阅读