gpt4 book ai didi

c - 如何在 C 中使用 malloc 和 realloc 读取和存储任意长度的字符串?

转载 作者:行者123 更新时间:2023-12-04 05:51:43 26 4
gpt4 key购买 nike

我有一个结构

typedef struct store
{
char name[11];
int age;
} store;

和一个主要功能(下面是它的一部分):
int main()
{
int i=0;
int inputs;
char line[100];
char name[11];
char command[11];
store read[3000];

while(i < 3000 && gets(line) != NULL)
{
int tempage;
inputs = sscanf(line, "%10s %10s %d", command, name, &tempage);
if (inputs == 3)
{
if (strcmp(command, "register") == 0)
{
strncpy(read[i].name, name,10);
read[i].age = tempage;
i++;
....

我需要修改它以便它可以读取任意长度的行,并使用 malloc 和 realloc 存储该行中的名称,该行也是任意长度的字符串。

我应该如何处理这个问题?

最佳答案

您需要做的是以较小的增量读取该行,并随时调整缓冲区的大小。

举个例子(没有经过测试,也没有特别优雅的意思,只是一个例子):

char *readline(FILE *f)
{
char *buf = NULL;
size_t bufsz = 0, len = 0;
int keep_going = 1;

while (keep_going)
{
int c = fgetc(f);
if (c == EOF || c == '\n')
{
c = 0; // we'll add zero terminator
keep_going = 0; // and terminate the loop afterwards
}

if (bufsz == len)
{
// time to resize the buffer.
//
void *newbuf = NULL;
if (!buf)
{
bufsz = 512; // some arbitrary starting size.
newbuf = malloc(bufsz);
}
else
{
bufsz *= 2; // issue - ideally you'd check for overflow here.
newbuf = realloc(buf, bufsz);
}

if (!newbuf)
{
// Allocation failure. Free old buffer (if any) and bail.
//
free(buf);
buf = NULL;
break;
}

buf = newbuf;
}

buf[len++] = c;
}

return buf;
}

关于c - 如何在 C 中使用 malloc 和 realloc 读取和存储任意长度的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9982548/

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