[[프로그래밍_NOTE]]/C , C++

fread() , fwrite()

갑빠돌격기 2008. 7. 26. 19:45
◎ fread() 함수는 화일로부터 이진 데이터나 구조체를 읽어들이기 위해 사용한다.

원형
size_t fread(void *ptr, size_t size, size_t nobj, FILE *fp);

인수
ptr - 화일에 읽은 자료를 저장할 버퍼의 시작주소
size - 입력 단위의 크기
nobj - 갯수
fp - 화일포인터

반환값
입력에 성공한 입력 단위의 갯수

◎ fwrite() 함수는 이진데이터나 구조체를 출력할 수 있도록하는 함수입니다.

원형
size_t fwrite(void *ptr, size_t size, size_t nobj, FILE *fp);

인수
ptr - 출력할 데이터의 시작주소
size - 출력 단위체의 크기
nobj - 갯수
fp - 화일포인터

반환값
출력에 성공한 대상체의 갯수




파일 오픈시 옵션은 바이너리로....
fp = fopen("map.txt","wb"); 

#include  <iostream.h>
#define     MAX        2

//struct//////////////////////////
struct emp
{
        char  name[10];
        int  phone;
        int  time;
        int  timepay;
} ;
/////////////////////////////////

int main()
{
        FILE  *fp,*fin;
        int  i,  j;
        emp  * employees  =  new  emp[MAX];
        emp  * temp           =  new  emp[MAX];

        for  (i=0;  i<MAX;  i++)  
        {
                printf("input  name:  ");
                scanf("%s",  employees[i].name);
   
                printf("input  phone:  ");
                scanf("%d",  &employees[i].phone);
   
                printf("input  time:  ");
                scanf("%d",  &employees[i].time);
   
                printf("input  timepay:  ");
                scanf("%d",  &employees[i].timepay);
        }
        cout  <<  endl;

        for  (i=0;  i<MAX;  i++)  
        {
                printf("input  name    :  %s  \n",  employees[i].name);
                printf("input  phone   :  %d  \n",  employees[i].phone);
                printf("input  time      :  %d  \n",  employees[i].time);
                printf("input  timepay :  %d  \n",  employees[i].timepay);
        }
        cout  <<  endl;

        if  (  (fp=  fopen("EMP.dat",  "wb"))==NULL  )  
        {
                printf("file  open  error");
                exit(1);
        }

// 1. 한개의 struct 씩 저장할때.. 이를 함수로 만들어 처리 하면 간편.
        for(i=0  ;  i<MAX  ;  i++)
                fwrite(&employees[i],sizeof(emp),1  ,fp);

// 2. 한꺼번에 쓰고자 할때.
// fwrite(employees,sizeof(emp),MAX ,fp);

        fclose(fp);
        
        if((fin  =  fopen("emp.dat","rb"))  ==  NULL)
        {
                exit(1);
        }

// 1. 한개의 struct 씩 읽고자할때.. 이를 함수로 만들어 처리 하면 간편.
        for(i=0  ;  i<MAX  ;  i++)
                fread(&temp[i],sizeof(emp),1,fin);

// 2. 한꺼번에 읽고자 할때.
// fread(temp,sizeof(emp),MAX,fin);
        for  (i=0;  i<MAX;  i++)  
        {
                printf("input  name:  %s  \n",  temp[i].name);
                printf("input  phone:  %d  \n",  temp[i].phone);
                printf("input  time:  %d  \n",  temp[i].time);
                printf("input  timepay:  %d  \n",  temp[i].timepay);
        }
        fclose(fin);

        delete  []  employees;
        delete  []  temp;
         
        return  0;
}