gpt4 book ai didi

c - 将 fgets 与 realloc() 结合使用

转载 作者:行者123 更新时间:2023-12-02 00:28:06 24 4
gpt4 key购买 nike

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

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

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

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

最佳答案

getline函数就是您要找的。

像这样使用它:

char *line = NULL;
size_t n;
getline(&line, &n, stdin);

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

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

关于c - 将 fgets 与 realloc() 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52984551/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com