小编Sph*_*ero的帖子

将 fgets 与 realloc() 结合使用

我正在尝试创建一个函数来从文本文件中读取一行,fgets()并将其存储在动态分配的 char* 中,malloc()但我不确定如何使用realloc(),因为我不知道这一行的长度文本,并且不想只是猜测该行可能的最大大小的幻数。

#include "stdio.h"
#include "stdlib.h"
#define INIT_SIZE 50

void get_line (char* filename)

    char* text;
    FILE* file = fopen(filename,"r");

    text = malloc(sizeof(char) * INIT_SIZE);

    fgets(text, INIT_SIZE, file);

    //How do I realloc memory here if the text array is full but fgets
    //has not reach an EOF or \n yet.

    printf(The text was %s\n", text);

    free(text);

int main(int argc, char *argv[]) {
    get_line(argv[1]);
}
Run Code Online (Sandbox Code Playgroud)

我计划用文本行做其他事情,但为了保持简单,我刚刚打印了它,然后释放了内存。

另外: main 函数是通过使用文件名作为第一个命令行参数来启动的。

c malloc realloc

3
推荐指数
1
解决办法
2729
查看次数

'break' 语句会分解多个 if 语句吗?

如果我有多个相互嵌套的 if 语句,它们都在 for 循环中,那么最里面的 if 语句上的 break 语句会跳出 for 循环还是直接进入下一个 if 语句?

c break

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

c ×2

break ×1

malloc ×1

realloc ×1