2012년 10월 9일 화요일

[C++] 파일 입출력 예제


1. 소스 내용
#include <iostream>
#include <cstdlib>
#include <fstream>
#include <io.h>
/* 
    윈도즈의 경우 access() 사용을 위해 io.h 가 필요 하나, linux 의 경우 io.h 가 없어도 컴파일이 된다.
*/

void readFile();
void createFile();

using namespace std;

int main() {

 int chk = access("c:\\d.txt", 0);
 // int chk = access("//home//freecatz//d.txt", 0);

 if (chk == 0) {
  cout << "file found" << endl;
  readFile();
 } else {
  cout << "file not found" << endl;
  createFile();
 }

 return 0;
}

void readFile() {
 ifstream file("c:\\d.txt");
// ifstream file("//home//freecatz//d.txt");

 char ch;

 while (!file.eof()) {
  file.get(ch);
  // getline() 에 대해서 알아 볼 것.

   cout << ch;
 }
}

void createFile() {
 ofstream file("c:\\d.txt");
// ofstream file("//home//freecatz//d.txt");

 file << "this is test file ...\nhello world" << endl;

 file.close();
}


2. 실행 결과

파일이 없는 경우 파일을 생성 하고, 파일이 있는 경우 화면에 뿌려 준다.

댓글 없음 :

댓글 쓰기