c++

11월 11일 파일의 존재 여부와 마지막 위치 확인

송시혁 2013. 11. 11. 18:54

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  ifstream input;
  
  input.open("FileTest.txt");

  //fail()함수는 반환형이 bool형이다. 
  //성공시 true, 실패시 false를 반환한다.
  //bool형의 크기는 1

  if(true==input.fail())//파일의 존재 여부 확인 if~else문
  {
    cout << "파일이 존재하지 않습니다!!" <<endl;
    return 0;
  }
  else
  {
    cout << "파일 열기 후 실행~~~ "<< endl;
    input.close();
  }

  return 0;
}
//---------------------------------------------------------------------------------------------------

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  ofstream output;  //출력 파일 객체 생성.
  char cont='y';
  char word[50]={0, };

  output.open("test.txt");

  if(true==output.fail())  //파일 존재 여부 확인 
  {
    return 1;
  }
  
  while(cont=='y'||cont=='Y')  
  {
    cout << "단어입력: ";
    cin >> word;    //키보드로부터 입력
    
    output << word << endl; 
    //변수 word는 출력 객체로서 내용을 파일에 저장한다.
    //endl을 받았으므로 엔터까지 저장된다.

    cout << "계속하시겠습니까? (y/n) ";
    cin >> cont;    
    //y나 대문자 Y를 누른경우 계속해서 while문을 반복하여
    //파일에 입력한 내용을 저장한다. 
  }  
  output.close();

  return 0;
}


//---------------------------------------------------------------------------------------------------

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
  ifstream input;    //입력 파일 객체 생성.(파일에서 읽어오기 위함.)
  char word[50]={0, };
  
  input.open("test.txt"); //
  if(true==input.fail())  //파일 존재 여부 검사.
  {
    return 1;
  }

  while(false==input.eof()) //파일의 끝이 아니면~~
  {
    input >> word;    //문자열 변수 word에 파일의 있는 문자열 저장.
    cout << word << endl; //화면에 출력.
  }
  input.close();

  return 0;
}

//객체.eof() 는 파일의 끝인지 아닌지 판단한다.
//반환형이 bool형이다.
//끝이면, true, 아니면 false를 반환한다.