#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// NOTE: dygetline() allocates memory! Do not disregard the return and
// remember to free() it when you're done!
#define BSZ 1024
char *dygetline(FILE * restrict stream) {
char *ret = NULL;
char *temp = NULL;
size_t retalloc = 1;
char buffer[BSZ];
size_t buflen = 0;
char *nlsrch;
while (NULL != fgets(buffer, BSZ, stream)) {
nlsrch = strrchr(buffer, '\n');
if (nlsrch) *nlsrch = '\0'; // Remove newline if exists
// Get the size of our read buffer and grow our return buffer
buflen = strlen(buffer);
temp = realloc(ret, retalloc + buflen);
if (NULL == temp) {
fprintf(stderr, "Memory allocation error in dygetline()!\n");
free(ret);
return NULL;
}
ret = temp; // Update return buffer pointer
strcpy((ret+retalloc-1), buffer); // Add read buffer to return buffer
retalloc = retalloc + buflen; // Housekeeping
if (nlsrch) break; // If we got a newline, stop
}
// If there was a file read error and fgets() never got anything, then
// ret will still be NULL, as it was initialized. If the file ended
// without a trailing newline, then ret will contain all characters it
// was able to get from the last line. Otherwise, it should be well-
// formed.
return ret;
}
1 回答
正如我在上面的评论中所说,这不是为了寻找 . 如果你想自己动手,那么这样做的方法是动态分配(和重新分配)内存来存储你从
fgets()
获得的结果 . 你可以判断fgets()
何时到达行的末尾,因为它要么突然到达文件的末尾(在这种情况下它将返回NULL
),或者因为它返回的最后一个字符将是换行符 .这是一个示例函数 . 请注意,我使用
strrchr()
从缓冲区末尾向后搜索换行符 . 如果我们得到一个命中,我们确保在返回的字符串中抛出换行符,并确保突破while()
循环,这样我们就不会再次调用fgets()
并开始获取下一行 .