fread

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

名前

fread, fwrite - バイナリストリームの入出力  

ライブラリ

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

書式

#include <stdio.h>

size_t fread(size_t size, size_t n;
             void ptr[restrict size * n],
             size_t size, size_t n,
             FILE *restrict stream);
size_t fwrite(size_t size, size_t n;
             const void ptr[restrict size * n],
             size_t size, size_t n,
             FILE *restrict stream);
 

説明

The function fread() reads n items of data, each size bytes long, from the stream pointed to by stream, storing them at the location given by ptr.

The function fwrite() writes n items of data, each size bytes long, to the stream pointed to by stream, obtaining them from the location given by ptr.

これらの処理を停止せずに行いたいときは、 unlocked_stdio(3) を参照のこと。  

返り値

成功すると、 fread() と fwrite() は読み書きを行った要素の個数を返す。 size が 1 の場合は、この数字は転送されたバイト数と等しい。 エラーが生じた場合や、ファイルの末尾 (end-of-file) に達した場合、 返り値は指定した個数よりも小さい値 (または 0) となる。

The file position indicator for the stream is advanced by the number of bytes successfully read or written.

fread() は end-of-file とエラーを区別しないので、 どちらが生じたかを判断するためには、 呼び出し側で feof(3) と ferror(3) とを使用しなければならない。  

属性

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

標準規格

C11, POSIX.1-2008.  

歴史

POSIX.1-2001, C89.  

例

The program below demonstrates the use of fread() by parsing /bin/sh ELF executable in binary mode and printing its magic and class:

$ ./a.out;
ELF magic: 0x7f454c46
Class: 0x02
 

プログラムのソース

#include <stdcountof.h>
#include <stdio.h>
#include <stdlib.h>

int
main(void)
{
    FILE           *fp;
    size_t         ret;
    unsigned char  buffer[4];

    fp = fopen("/bin/sh", "rb");
    if (!fp) {
        perror("fopen");
        return EXIT_FAILURE;
    }

    ret = fread(buffer, sizeof(*buffer), countof(buffer), fp);
    if (ret != countof(buffer)) {
        fprintf(stderr, "fread() failed: %zu\n", ret);
        exit(EXIT_FAILURE);
    }

    printf("ELF magic: %#04x%02x%02x%02x\n", buffer[0], buffer[1],
           buffer[2], buffer[3]);

    ret = fread(buffer, 1, 1, fp);
    if (ret != 1) {
        fprintf(stderr, "fread() failed: %zu\n", ret);
        exit(EXIT_FAILURE);
    }

    printf("Class: %#04x\n", buffer[0]);

    fclose(fp);

    exit(EXIT_SUCCESS);
}
 

関連項目

read(2), write(2), feof(3), ferror(3), unlocked_stdio(3)


 

Index

名前
ライブラリ
書式
説明
返り値
属性
標準規格
歴史
例
プログラムのソース
関連項目

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