我很困惑。
我查看了链接,阅读了描述,这是一个很好的实用程序。
但是,你是说你根本无法将这个函数重写为规范吗?规格似乎很清楚,
在这里:
/* This code is public domain -- Will Hartung 4/9/09 */
#include <stdio.h>
#include <stdlib.h>
size_t getline(char **lineptr, size_t *n, FILE *stream) {
char *bufptr = NULL;
char *p = bufptr;
size_t size;
int c;
if (lineptr == NULL) {
return -1;
}
if (stream == NULL) {
return -1;
}
if (n == NULL) {
return -1;
}
bufptr = *lineptr;
size = *n;
c = fgetc(stream);
if (c == EOF) {
return -1;
}
if (bufptr == NULL) {
bufptr = malloc(128);
if (bufptr == NULL) {
return -1;
}
size = 128;
}
p = bufptr;
while(c != EOF) {
if ((p - bufptr) > (size - 1)) {
size = size + 128;
bufptr = realloc(bufptr, size);
if (bufptr == NULL) {
return -1;
}
}
*p++ = c;
if (c ==
) {
break;
}
c = fgetc(stream);
}
*p++ = ;
*lineptr = bufptr;
*n = size;
return p - bufptr - 1;
}
int main(int argc, char** args) {
char *buf = NULL; /*malloc(10);*/
int bufSize = 0; /*10;*/
printf("%d
", bufSize);
int charsRead = getline(&buf, &bufSize, stdin);
printf(" %s ", buf);
printf("%d
", bufSize);
return 0;
}
15分钟,我已经10年没有写过C了。它略微破坏了getline约定,因为它只检查lineptr是否为NULL,而不是NULL和n=0。如果你愿意,你可以解决这个问题。(另一种情况对我来说意义不大,我想在这种情况下你可以返回-1。)
Replace the
with a variable to implement "getdelim".
人们还会写代码吗?