fread
The fread
function is useful when you need to read non-textual data (binary data) from a file, such as images, videos, or sound files, where data is stored in a binary format. In such files, instead of writing the textual representation of data (like integers), the raw bytes are written directly. The specific size of data items is part of the file format specification. The fread
function is commonly used for this purpose and has the following prototype:
size_t fread (void * ptr, size_t size, size_t nitems, FILE * stream);
Here’s a breakdown of the arguments:
void *
because it could be any type of data (e.g., int, float, struct).sizeof(int)
. For better compatibility across systems, it’s advisable to use fixed-size types like int32_t
or uint64_t
from stdint.h
.Return Value:
The function returns how many items were successfully read. If fewer items are read than requested, you should check for errors using feof
(for end-of-file) and/or ferror
.
Additionally, there is a function called fscanf
that reads formatted input and converts it, similar to what printf
does in reverse. However, using fgets
(or later, getline
) along with sscanf
is often simpler and less error-prone when reading formatted input. With fgets
, you can read an entire line, and then attempt to parse the line using sscanf
, which allows you to handle input that may not perfectly match the expected format. On the other hand, fscanf
stops reading as soon as it encounters an unexpected format, requiring you to manually skip the rest of the line before proceeding.
For more details on fscanf
or sscanf
, refer to their man pages.
fread
로 파일 읽기fread
함수는 이미지, 비디오, 사운드 파일처럼 바이너리 데이터를 읽을 때 유용합니다. 이러한 파일은 데이터를 텍스트 형식으로 저장하는 대신 실제 바이트 단위로 저장합니다. fread
함수는 이러한 데이터를 읽을 때 사용되며, 다음과 같은 프로토타입을 가지고 있습니다:
size_t fread (void * ptr, size_t size, size_t nitems, FILE * stream);
각 인수의 설명은 다음과 같습니다:
void *
타입이므로 다양한 데이터 유형을 처리할 수 있습니다.sizeof(int)
를 사용합니다. 시스템 간 호환성을 고려해 stdint.h
의 int32_t
또는 uint64_t
와 같은 고정 크기 유형을 사용하는 것이 좋습니다.