将 fgets 与 realloc() 结合使用

Sph*_*ero 3 c malloc 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 函数是通过使用文件名作为第一个命令行参数来启动的。

Mat*_*ieu 5

getline函数正是您所寻找的。

像这样使用它:

char *line = NULL;
size_t n;
getline(&line, &n, stdin);
Run Code Online (Sandbox Code Playgroud)

如果你真的想自己实现这个功能,你可以这样写:

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

char *get_line()
{
    int c;
    /* what is the buffer current size? */
    size_t size = 5;
    /* How much is the buffer filled? */
    size_t read_size = 0;
    /* firs allocation, its result should be tested... */
    char *line = malloc(size);
    if (!line) 
    {
        perror("malloc");
        return line;
    }

    line[0] = '\0';

    c = fgetc(stdin);
    while (c != EOF && c!= '\n')
    {            
        line[read_size] = c;            
        ++read_size;
        if (read_size == size)
        {
            size += 5;
            char *test = realloc(line, size);
            if (!test)
            {
                perror("realloc");
                return line;
            }
            line = test;
        }
        c = fgetc(stdin);
    }
    line[read_size] = '\0';
    return line;
}
Run Code Online (Sandbox Code Playgroud)

  • @Someprogrammerdude“POSIX”和“不可移植”在术语上有些矛盾。仅当“不可移植”实际上意味着“几乎在任何地方都可用,但在 Windows 上不可用”时,这才是正确的。 (3认同)
  • 请注意,“getline”是仅 POSIX 函数,不可移植。 (2认同)