#include <stdio.h>
ssize_t getline(char **restrict lineptr, size_t *restrict n,
FILE *restrict stream);
ssize_t getdelim(char **restrict lineptr, size_t *restrict n,
int delim, FILE *restrict stream);
glibc 向けの機能検査マクロの要件 (feature_test_macros(7) 参照):
getline(), getdelim():
Since glibc 2.10:
_POSIX_C_SOURCE >= 200809L
Before glibc 2.10:
_GNU_SOURCE
If *lineptr is set to NULL before the call, then getline() will allocate a buffer for storing the line. This buffer should be freed by the user program even if getline() failed.
別の方法として、 getline() を呼び出す際に、 *lineptr に malloc(3) で確保した大きさ *n バイトのバッファーへのポインターを入れて渡すこともできる。 読み込んだ行を保持するのに十分なバッファーがない場合、 getline() は realloc(3) を使ってバッファーのサイズを変更し、必要に応じて *lineptr と *n を更新する。
どちらの場合でも、呼び出しに成功したときには、 *lineptr と *n がバッファーのアドレスと割り当てたサイズを反映した値に更新される。
getdelim() は getline() と同じように動作するが、改行文字以外の区切り文字を引数 delim に指定することができる。 getline() と同様に、ファイル終端に達するまでに入力行に区切り文字が見付からない場合は、 区切り文字をバッファーに追加しない。
At end of file, both functions return -1 with the file stream end-of-file indicator set. On error, both functions return -1 with the file stream error indicator set, and errno is set to indicate the error.
If *lineptr was set to NULL before the call, then the buffer should be freed by the user program even on failure.
| インターフェース | 属性 | 値 |
| getline(), getdelim() | Thread safety | MT-Safe |
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[])
{
FILE *stream;
char *line = NULL;
size_t size = 0;
ssize_t nread;
if (argc != 2) {
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
exit(EXIT_FAILURE);
}
stream = fopen(argv[1], "r");
if (stream == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
while ((nread = getline(&line, &size, stream)) != -1) {
printf("Retrieved line of length %zd:\n", nread);
fwrite(line, nread, 1, stdout);
}
free(line);
fclose(stream);
exit(EXIT_SUCCESS);
}