Soft Ware/C 언어!!

구조체 배열을 이용하여 파일에 쓰기 !!!

달려가보자 2012. 1. 31. 16:19


#include <iostream>
#include <stdio.h>
#include <sys/stat.h>
#include <io.h>
#include <fcntl.h>
 
using namespace std;

#define MAX 3
typedef struct List
{
 bool a;
 bool b;
 char buffer[20];
}List;

int main()
{
 List a[MAX];
 List b[MAX];
 int handle = 0;
 int rehandle = 0;
 int reData = 0;
 long lenData = 0;


 for(int i=0;i<MAX;i++)
 {
  memset(a+i,0,sizeof(List));
  memset(b+i,0,sizeof(List));
 }
 
 a[0].a = 1;
 a[0].b = 0;
 strcpy(a[0].buffer,"조정근");
 a[1].a = 1;
 a[1].b = 0;
 strcpy(a[1].buffer,"이완상");
 a[2].a = 1;
 a[2].b = 0;
 strcpy(a[2].buffer,"송은남");

 handle = _open("test",O_BINARY|O_RDWR|O_CREAT,S_IWRITE);

 try
 {
  if(handle == -1) throw ;

  for(int i=0;i<MAX;i++)
  {
   write(handle,a+i,sizeof(a[i]));
  }
 
 
  //close(handle);
 }

 catch(...)
 {
  cout<<"file open false"<<endl;
  exit(0);
 }
 
 //rehandle = _open("test",O_BINARY|_O_RDONLY);

 if(rehandle == -1)
 {
  cout<<"file2 open false"<<endl;
  exit(0);
 }

 lseek(handle,0,SEEK_SET);
 cout<< "FP : " <<lenData<<endl;
 read(handle,&b,sizeof(List)*MAX);

 cout<<b[0].a <<b[0].b<<b[0].buffer<<endl;
 cout<<b[1].a <<b[1].b<<b[1].buffer<<endl;
 cout<<b[2].a <<b[2].b<<b[2].buffer<<endl;
 //close(rehandle);
}