반응형
fwrite(3)
#include <stdio.h>
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream);
open된 stream으로 바이너리 데이터를 쓰기를 수행합니다. size 크기의 데이터를 nmemb 회수만큼 ptr에서 stream으로 쓰기를 수행합니다. return 값은 byte수가 아닌 size의 크기로 몇 개 write되었는 지를 return합니다. write된 전체 byte수는 return값 * size입니다.
파라미터
ptr
- file에 write할 데이터를 저장하고 있는 buffer입니다.
size
- 한 개의 item의 크기(byte수)입니다.
- 파일에 구조체를 통째로 write한다면 sizeof(구조체)로 합니다.
nmemb
- file에 write할 item의 갯수입니다.
- 파일에 구조체를 저장한다면 한번에 쓸 구조체 갯수를 설정합니다.
stream
- fopen(3), fdopen(3) 등으로 생성한 FILE *입니다.
RETURN
nmemb
- nmemb 수 만큼 정상적으로 모두 file로 write하였습니다.
nmemb 보다 작을 때
- 오류가 발생하여 전체 데이터를 쓰지 못하였습니다.
- 오류 내용은 ferror(3)함수를 통하여 확인해야 합니다.
활용 예제
Sample : 파일을 복사하는 프로그램
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[])
{
FILE *wfp, *rfp;
char buffer[4096];
int size;
char sfile[1024];
char dfile[1024];
......
if(argc != 3) {
fprintf(stderr, "Usage:\n\t%s src_file dest_file\n\t파일을 복제합니다.\n", argv[0]);
return 1;
}
strcpy(sfile, argv[1]);
strcpy(dfile, argv[2]);
if((rfp = fopen(sfile, "r")) == NULL) {
fprintf(stderr, "%s file open error: %s\n", sfile, strerror(errrno));
return 1;
}
if((rfp = fopen(dfile, "w")) == NULL) {
fprintf(stderr, "%s file open error: %s\n", dfile, strerror(errrno));
return 1;
}
while((size = fread(buffer, 1, 4096, rfp)) > 0) {
fwrite(buffer, 1, size, wfp);
}
fclose(rfp);
fclose(wfp);
return 0;
}
see also :
반응형
'C언어 header > stdio.h' 카테고리의 다른 글
ungetc(3) - stream으로 1 byte 되돌리기 (0) | 2019.09.24 |
---|---|
fgetc(3) - stream으로부터 1byte 읽기 (0) | 2019.09.24 |
fread(3) - binary stream 읽기 (0) | 2019.09.24 |
fclose(3) - open된 stream 닫기 (0) | 2019.09.24 |
fopen(3) - 읽기/쓰기 위해 파일을 열기 (0) | 2019.09.24 |