file access 예제

Download Report

Transcript file access 예제

File 저장
 파일에 데이터 저장 및 불러오기
• C의 표준 Library 사용 : fopen, fclose, fprintf, fscanf, …
• MFC의 CFile class 사용
• MFC의 CArchive 클래스와 CFile 클래스를 연결해서 사용
 C의 표준 Library를 사용한 파일 writing 예제
int a = 3;
aaa.txt
FILE *fp;
fp = fopen(“aaa.txt”, “w”);
hello, world
fprintf(fp, “hello, world\n”);
3
fprintf(fp, “%d”, a);
fclose(fp);
프로그래밍 응용 #19
1
C 표준 라이브러리를 사용한 파일 입출력
 FILE *fopen(char *filename, char *mode)
• filename을 가지는 파일을 open함
• mode : “r” (read), “w” (write), “a” (append)
 int fclose(FILE *fp)
• fopen한 파일은 맨 마지막에 close를 해 주어야 됨
 int fprintf(FILE *fp, char *format, ….)
• file pointer fp가 가르키는 파일에 데이터를 writing 함
 int fscanf(FILE *fp, char *format, …)
• file pointer fp가 가르키는 파일에서 데이터를 reading 함
프로그래밍 응용 #19
2
file access 예제 : lecture192
 숫자 3개를 읽음 : 변수 a,b,c에 3,6,7의 값이 들어감.
int a, b, c;
FILE *fp;
fp = fopen(“aaa.txt”, “r”);
fscanf(fp, “%d %d %d”,&a,&b,&c);
aaa.txt
367
fclose(fp);
 파일 2개 이상 open : “aaa.txt”, “bbb.txt”
FILE *fp1, *fp2;
fp1 = fopen(“aaa.txt” , “r”);
fp2 = fopen(“bbb.txt” , “w”);
…
프로그래밍 응용 #19
3
사각형 그리기에 Save 및 Open 기능 추가
 사각형 그리기
void CLecture192View::OnLButtonDown(UINT nFlags, CPoint point)
{
m_p[m_count] = point;
++m_count;
Invalidate();
}
void CLecture192View::OnDraw(CDC* pDC)
{
int i;
for ( i = 0 ; i < m_count ; ++i )
pDC->Rectangle(m_p[i].x - 5,m_p[i].y - 5,m_p[i].x + 5,m_p[i].y + 5);
}
프로그래밍 응용 #19
4
점 정보를 저장함
 OnMySave
void CLecture192View::OnMysave()
{
FILE *fp;
int i;
fp = fopen("aaa.txt","w");
fprintf(fp,"%d\n",m_count);
for ( i = 0 ; i < m_count ; ++i )
fprintf(fp,"%d %d\n",m_p[i].x,m_p[i].y);
aaa.txt
7
281 201
385 254
464 335
268 398
169 357
166 235
155 152
fclose(fp);
}
프로그래밍 응용 #19
5
저장된 데이터를 불러옴
void CLecture192View::OnMyopen()
{
FILE *fp;
int i;
if ( (fp = fopen("aaa.txt","r")) == NULL )
return;
fscanf(fp,"%d\n",&m_count);
for ( i = 0 ; i < m_count ; ++i )
fscanf(fp,"%d %d\n",&(m_p[i].x),&(m_p[i].y));
aaa.txt
7
281 201
385 254
464 335
268 398
169 357
166 235
155 152
fclose(fp);
Invalidate();
}
프로그래밍 응용 #19
6
실습문제 : 데이터 저장
aaa.txt
void CLecture192View::OnMysave()
{
FILE *fp;
int i;
fp = fopen("aaa.txt","w");
for ( i = 0 ; i < 7 ; ++i )
fprintf(fp,"%d %d %d\n",i,2*i,3*i);
fclose(fp);
}
프로그래밍 응용 #19
7
file access 예제 : lecture193
 MFC class CFile을 사용하여 파일을 access
 OnMySave()
void CLecture192View::OnMysave()
{
CFile file;
file.Open("aaa.dat",CFile::modeCreate | CFile::modeWrite );
file.Write(&m_count,sizeof(int));
file.Write(m_p, m_count*sizeof(CPoint));
file.Close();
}
• binary 형식의 파일이 생성됨
프로그래밍 응용 #19
8
파일 접근 모드
 Open 시의 접근 모드
접근모드
설명
CFile::modeRead
파일을 읽기만 할 수 있음
CFile::modeWrite
파일을 쓰기만 할 수 있음
CFile::modeReadWrite
읽고 쓰기를 모두 할 수 있음
CFile::modeCreate
파일을 새로 생성
CFile::modeNoTruncate
기존에 있는 파일의 맨 뒤에 데이터를 추가
 Write( 저장할 데이터의 주소, 데이터의 크기의 바이트 단위)
int m_count; CPoint m_p[100];
file.Write(&m_count,sizeof(int));
file.Write(m_p, m_count*sizeof(CPoint));
프로그래밍 응용 #19
// array  m_p == &m_p[0]
9
OnMyOpen
void CLecture192View::OnMyopen()
{
CFile file;
file.Open("aaa.dat",CFile::modeRead );
file.Read(&m_count,sizeof(int));
file.Read(m_p, m_count*sizeof(CPoint));
file.Close();
Invalidate();
}
 Read ( 저장할 데이터의 주소, 데이터의 크기의 바이트 단위)
프로그래밍 응용 #19
10
OnMyOpen2
 Open 함수는 성공시에 0이 아닌 숫자를 실패시에는 0을 return 함
 실패시를 대비한 routine (예: aaa.dat 파일이 존재하지 않음)
void CLecture192View::OnMyopen2()
{
CFile file;
if ( file.Open("aaa.dat",CFile::modeRead ) ) {
file.Read(&m_count,sizeof(int));
file.Read(m_p, m_count*sizeof(CPoint));
file.Close();
Invalidate();
}
else
AfxMessageBox("File Reading Error");
}
프로그래밍 응용 #19
11
Dialog Box를 사용해서 파일 이름 지정 (lecture194)
 File Name을 입력받는 dialog box를 하나 만듬
void CLecture192View::OnMyopen()
{
CNameDlg dlg;
CNameDlg
m_name
CFile file;
if ( dlg.DoModal() != IDOK )
return;
if ( file.Open(dlg.m_name,CFile::modeRead ) == 0 )
return;
file.Read(&m_count,sizeof(int));
file.Read(m_p, m_count*sizeof(CPoint));
file.Close();
Invalidate();
}
프로그래밍 응용 #19
12
CFileDialog class
 CFileDialog class
• 파일이름을 선택하여 주는 MFC의 class
• 파일이름만 선택하여 주고 실제로 파일 open 등을 하는 것은 아님
void CLecture192View::OnMyopen2()
{
CFile file;
char szFilter[] = "Data File(*.dat)|*.dat| |";
CFileDialog dlg(TRUE,NULL,NULL,OFN_HIDEREADONLY,szFilter);
if ( dlg.DoModal() != IDOK )
return;
if ( file.Open( dlg.GetPathName() ,CFile::modeRead ) == 0 )
return;
file.Read(&m_count,sizeof(int));
file.Read(m_p, m_count*sizeof(CPoint));
file.Close();
Invalidate();
}
프로그래밍 응용 #19
13
CFileDialog class
 CFileDialog의 생성자
CFileDialog(BOOL bOpenFileDialog, LPCTSTR lpszDefExt=NULL,
LPCTSTR lpszFileName = NULL,
DWORD dwFlags = OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT,
LPCTSTR lpszFilter = NULL, CWnd *pParentWnd = NULL);
 bOpenFileDialog : TRUE를 넣어주면 대화상자 타이틀바에 “열기”라고 출력되고,
FALSE를 주면, “다른 이름으로 저장”이라고 출력됨
 lpszDefExt : 기본 확장자. 여기에 “dat”를 지정해 두면 사용자가 test라고만 입력하
면 파일명이 자동으로 test.dat로 바뀌게 됨
 lpszFileName : 대화상자가 처음 출력되었을 때, “파일 이름” Edit 컨트롤에 출력될
파일명을 지정
 lpszFilter : 확장자에 대한 필터
• “source file(*.cpp), header file(*.h) | *.cpp ; *h| all files(*.*) | *.*| |”
프로그래밍 응용 #19
14
CFileDialog class
 dwFlags
플래그
의미
OFN_EXPLORER
윈도우 탐색기 스타일
OFN_ARROWMULTISELECT
파일을 한 번에 여러 개 선택 가능
OFN_CREATEPROMPT
존재하지 않는 파일명을 입력  메시지 박스 출력하여 확인
OFN_FILEMUSTEXIST
존재하지 않는 파일명을 입력할 수 없도록 함
OFN_HIDEREADONLY
읽기 전용 파일은 출력 안 함
OFN_LONGNAMES
긴 파일 이름 포맷을 지원하도록 함
OFN_OVERWRITEPROMPT
존재하는 파일 입력시 덮어쓰겠냐는 메시지 박스 출력
OFN_PATHMUSTEXIST
이미 존재하는 디렉토리명만을 입력 가능
프로그래밍 응용 #19
15
CFileDialog class
 멤버함수
• CString GetPathName() : Path를 포함한 파일 이름
- “C:\work\aaa.dat”
• CString GetFileName() : 파일 이름만
- “aaa.dat”
• CString GetFileTitle() : 파일 이름만 (확장자 제외)
- “aaa”
• CString GetFileExt() : 확장자만
- “dat”
프로그래밍 응용 #19
16