- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我必须创建一个 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/
我尝试学习C语言。我成功创建了一个程序,该程序逐行读取并将其返回到终端。不幸的是,当我检查 valgrind 时,仍然存在一些泄漏问题。你有什么建议吗? #include "get_next_line
我必须创建一个 C 函数,它返回从文件描述符读取的一行。我必须定义一个宏 READ_SIZE(可以编辑)。此 READ_SIZE 表示每次调用 read() 时要读取的字符数。数字只能是正数。 我还必
我的函数是一个字符一个字符地读取,所以它不能使用多个缓冲区大小,我需要帮助来修复它,以便它可以使用任何缓冲区大小,而不仅仅是 1。 所以主要问题是它应该使用缓冲区大小而不是逐个字符 我试图读取更改缓冲
我是一名优秀的程序员,十分优秀!