繁体   English   中英

未确定长度的字符串 c

[英]string of undetermined length c

嗨,我试图在 c 中创建一个长度未定的字符串数组。 这是我的代码:

    int main()
    {
        int lineCount=linesCount();
        char text[lineCount][10];
        printf("%d",lineCount);
        FILE *  fpointer = fopen("test.txt","r");
        fgets(text,10,fpointer);
        fclose(fpointer);
        printf("%s",text);
        return 0;
    }

我想更换 10 在

    char text[lineCount][10];

我的代码读出了一个我已经使行数动态的文件。 由于行长是不可预测的,我想用动态的东西替换 10 。 提前致谢。

为了清楚地做到这一点,我们需要一个char *数组而不是 2D char数组:

char *text[lineCount];

而且,我们需要使用堆中的 memory 来存储各个行。

另外,不要“硬连线”所谓的“魔术”数字,例如10 使用enum#define (例如) #define MAXWID 10 请注意,使用下面的解决方案,我们完全不需要使用幻数。

另外,请注意下面使用sizeof(buf)而不是幻数。

而且,我们希望在阅读和打印时使用 [单独的] 循环。

无论如何,这是重构的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
linesCount(void)
{

    return 23;
}

int
main(void)
{
    int lineCount = linesCount();
    char *text[lineCount];
    char buf[10000];

    printf("%d", lineCount);

    // open file and _check_ the return
    const char *file = "test.txt";
    FILE *fpointer = fopen(file, "r");
    if (fpointer == NULL) {
        perror(file);
        exit(1);
    }

    int i = 0;
    while (fgets(buf, sizeof(buf), fpointer) != NULL) {
        // strip newline
        buf[strcspn(buf,"\n")] = 0;

        // store line -- we must allocate this
        text[i++] = strdup(buf);
    }

    fclose(fpointer);

    for (i = 0;  i < lineCount;  ++i)
        printf("%s\n", text[i]);

    return 0;
}

更新:

以上代码来源于您的原始代码。 但是,它假设linesCount function 可以预测行数。 而且,它不检查固定长度text数组的溢出。

这是一个更通用的版本,它允许任意数量的具有不同行长的行:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int
main(void)
{
    int lineCount = 0;
    char **text = NULL;
    char buf[10000];

    // open file and _check_ the return
    const char *file = "test.txt";
    FILE *fpointer = fopen(file, "r");
    if (fpointer == NULL) {
        perror(file);
        exit(1);
    }

    int i = 0;
    while (fgets(buf, sizeof(buf), fpointer) != NULL) {
        // strip newline
        buf[strcspn(buf,"\n")] = 0;

        ++lineCount;

        // increase number of lines in array
        text = realloc(text,sizeof(*text) * lineCount);
        if (text == NULL) {
            perror("realloc");
            exit(1);
        }

        // store line -- we must allocate this
        text[lineCount] = strdup(buf);
    }

    fclose(fpointer);

    // print the lines
    for (i = 0;  i < lineCount;  ++i)
        printf("%s\n", text[i]);

    // more processing ...

    // free the lines
    for (i = 0;  i < lineCount;  ++i)
        free(text[i]);

    // free the list of lines
    free(text);

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM