如何在每个字符读取文件char时为字符串动态分配缓冲区?

时间:2016-04-19 17:28:24

标签: c string malloc

如何在每个字符读取文件字符时为字符串动态分配缓冲区?

我目前使用的是malloc 1000(作为字符串的限制),但它对我来说似乎不是一个正确的解决方案。

int charIter = 0;

FILE *fp = fopen(fileName, "r");

    if (!fp)
        error(404);
    else
    {
        buffer = (char*)malloc(1000 * sizeof(char*)); //I want this dynamically

        countSntcs = countSentences(fp); // returns number of sntcs in file
        sentences = (char**)malloc(countSntcs * sizeof(char*));

        while ((c = fgetc(fp)) != EOF)
        {
            tolower(c);
            if ((c == '\n') || (skip))
            {
                skip = FALSE;
            } 
            else if ((c == '?') || (c == '.') || (c == '!'))
            {
                lenght = countLenght(fp, iterator);
                iterator += lenght;
                sentences[w] = (char*)malloc(lenght * sizeof(char*));
                buffer[charIter++] = c;
                buffer[charIter] = '\0';
                charIter = 0;
                strcpy(sentences[w], buffer);
                w++;
                skip = TRUE;
            }
            else
            {
                buffer[charIter++] = c;
            }
        }
        fclose(fp);
    }

0 个答案:

没有答案