반응형

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 :

    File 속성 정보 및 파일 관리 Library

    Directory 정보 조회 및 관리 Library

    System Call File I/O Library

    Stream File I/O Library

 

 

반응형
블로그 이미지

자연&사람

행복한 개발자 programmer since 1995.

,