我目前正在进行的实验使用的软件基础具有复杂的源历史记录并且没有明确定义的许可证。合理化事情并在固定许可证下发布将需要大量的工作。
它还旨在运行一个随机的 unixish 平台,并且只有我们支持的一些 libc 具有 GNU getline,但现在代码期望它。
有谁知道重新实施GNU getline http://www.gnu.org/software/hello/manual/libc/Line-Input.html在限制较少的许可下可用的语义?
Edit::我问是因为谷歌没有帮助,如果可能的话我想避免写一个(这可能是一个有趣的练习,但它不能是我时间的最佳利用。)
更具体地说,有问题的接口是:
ssize_t getline (char **lineptr, size_t *n, FILE *stream);
Will Hartung 的代码存在一个非常严重的问题。realloc
很可能会释放旧块并分配一个新块,但是p
代码中的指针将继续指向原来的。本文试图通过使用数组索引来解决这个问题。它还尝试更接近地复制标准 POSIX 逻辑。
/* The original code is public domain -- Will Hartung 4/9/09 */
/* Modifications, public domain as well, by Antti Haapala, 11/10/17
- Switched to getc on 5/23/19 */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <stdint.h>
// if typedef doesn't exist (msvc, blah)
typedef intptr_t ssize_t;
ssize_t getline(char **lineptr, size_t *n, FILE *stream) {
size_t pos;
int c;
if (lineptr == NULL || stream == NULL || n == NULL) {
errno = EINVAL;
return -1;
}
c = getc(stream);
if (c == EOF) {
return -1;
}
if (*lineptr == NULL) {
*lineptr = malloc(128);
if (*lineptr == NULL) {
return -1;
}
*n = 128;
}
pos = 0;
while(c != EOF) {
if (pos + 1 >= *n) {
size_t new_size = *n + (*n >> 2);
if (new_size < 128) {
new_size = 128;
}
char *new_ptr = realloc(*lineptr, new_size);
if (new_ptr == NULL) {
return -1;
}
*n = new_size;
*lineptr = new_ptr;
}
((unsigned char *)(*lineptr))[pos ++] = c;
if (c == '\n') {
break;
}
c = getc(stream);
}
(*lineptr)[pos] = '\0';
return pos;
}
通过锁定流一次并使用等效的方法可以提高平台的性能getc_unlocked(3) https://pubs.opengroup.org/onlinepubs/009695399/functions/getc_unlocked.html- 但这些在 C 中没有标准化;如果你使用的是 POSIX 版本,那么你可能会有getline(3) https://pubs.opengroup.org/onlinepubs/9699919799/functions/getdelim.html已经。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)