gpt4 book ai didi

c - C 中 Get_Next_Line 的无限循环

转载 作者:行者123 更新时间:2023-12-01 09:16:43 26 4
gpt4 key购买 nike

我必须创建一个 C 函数,它返回从文件描述符读取的一行。我必须定义一个宏 READ_SIZE(可以编辑)。此 READ_SIZE 表示每次调用 read() 时要读取的字符数。数字只能是正数。

我还必须使用一个或多个静态变量来保存已读取但未发送回调用函数的字符。一个 .C 文件(最多 5 个函数,每个函数最多 25 行)和一个 .h 文件。

我的函数 Get_Next_Line 应返回不带“\n”的返回值。如果在文件描述符上没有更多可读取的内容,或者读取时发生错误,则该函数返回 NULL。

函数原型(prototype)如下:

char *get_next_line(const int fd)

FUNCTIONS ALLOWED: malloc, free, read, write (to use with my_putchar, my_putstr, etc).

这是我拥有的,但它不起作用。它做了一个无限循环我想知道为什么。

char        *my_strcat(char *str1, char *str2)
{
int i;
int j;
int s;
char *strfinal;

i = 0;
j = 0;
s = 0;
if ((strfinal = malloc(sizeof(char) * (my_strlen(str1) + my_strlen(str2)
+ 1))) == NULL)
return (NULL);
while (str1[i] != '\0')
{
strfinal[j] = str1[i];
i++;
j++;
}
while (str2[s] != '\0')
{
strfinal[j] = str2[s];
s++;
j++;
}
free(str1);
strfinal[j] = '\0';
return (strfinal);
}

char *get_next_line(const int fd)
{
int n;
int i;
char *str_to_return;
static char buff[READ_SIZE] = {'\0'};

n = 1;
i = 0;
str_to_return = NULL;
while (n)
{
if (i == 0 && buff == '\0')
{
if ((read(fd, buff, READ_SIZE)) <= 0)
return(str_to_return);
if (i == READ_SIZE - 1 || buff[i] == '\n')
{
n = 0;
str_to_return = my_strcat(buff, str_to_return);
i = -1;
}
}
i++;
}
printf("%s\n", str_to_return);
return (str_to_return);
}

最佳答案

在这段代码中:

while (str1[i] != '\0')
{
strfinal[j] = str1[i];
i++;
j++;
}

你有什么保证 str1[] 中的某处会有空字符 \0 ???

str2 while 循环也是如此。如果没有遇到空字符,就会死循环。

验证您用于将字符填充到内存中的函数 str1[]str2[] 包括空字符。由于您之前仅使用 read() 函数,因此答案是否定的。

str1[]str2[] 的两个 while 循环的问题是您依赖空字符已经存在于内存中。这就引出了一个问题,谁将这些数据放在内存中,他们是否被要求以空字符终止字符数据?因此,您需要以某种方式控制您编写的任何循环,以免陷入无限循环;在这种情况下,可能会使用一个计数器,并且在 i 访问 str1[i] 这么多次之后停止,因为您还没有看到空字符。

例如,fgets() 函数将从一个 FILE 流中读取如此多的字符到一个数组中,并且总是以空字符终止它。

关于c - C 中 Get_Next_Line 的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35780009/

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