getline

Section: C Library Functions (3)
Updated: 2026-02-08
Index JM Home Page roff page
 

名前

getline, getdelim - 区切り文字までの文字列入力を読み込む  

ライブラリ

標準 C ライブラリ (libc,~-lc)  

書式

#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
 

説明

getline() は stream から 1 行全てを読み込み、テキストが含まれているバッファーのアドレスを *lineptr に格納する。 バッファーはヌル文字 (\0) で終端される。 改行文字が見つかった場合は、改行文字もバッファーに格納される。

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() と同様に、ファイル終端に達するまでに入力行に区切り文字が見付からない場合は、 区切り文字をバッファーに追加しない。  

返り値

On success, getline() and getdelim() return the number of characters read, including the delimiter character, but not including the terminating null byte ('\0'). This value can be used to handle embedded null bytes in the line read.

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.  

エラー

EINVAL
引数が不正である (n または lineptr が NULL である。 もしくは stream が有効でない)。
ENOMEM
Allocation or reallocation of the line buffer failed.
 

属性

この節で使用されている用語の説明については、 attributes(7) を参照。
インターフェース属性値
getline(), getdelim() Thread safetyMT-Safe
 

標準規格

POSIX.1-2008.  

歴史

GNU, POSIX.1-2008.  

例

#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);
}
 

関連項目

read(2), fgets(3), fopen(3), fread(3), scanf(3)


 

Index

名前
ライブラリ
書式
説明
返り値
エラー
属性
標準規格
歴史
例
関連項目

This document was created by man2html, using the manual pages.