[C++/리팩토링] ofstream을 class 멤버로 사용하려면 어떻게 해야할까요?

조회수 1837회

아래 코드가 동작은 하는 코드이긴 하지만 가독성이 너무 떨어집니다. 파일 스트림 부분이 나눠서 작성되어 있기도 하고 중복되는 부분 때문인듯 합니다.

제 아이디어로는 파일 스트림부분을 클래스 멤버 변수?(함수?) 로 사용하고 파일이 열수있는지 체크하는 부분을 함수로 만들면 될 것 같긴한데 초보자라 어떻게 손을 대야할지 모르겠습니다.

void RegisterAccount::createAccount() {
    ofstream accountFile("pass.dat", ios::out /*| ios::binary */ | ios::app);   // ID 와 암호화된 비번이 기록될 파일
    if (!accountFile) {
        cerr << "File could not be opened" << endl;
        exit(EXIT_FAILURE);
    } // 파일스트림 부분의 코드를 깔끔하게 정리할 수 있는 방법은 뭘까요..

    if (inputID() == true) {    // getID()에 userID가 들어오는 시점

        string fileNameToUserName = (getID() + ".dat"); 
        ofstream userInfoFile(fileNameToUserName.c_str(), ios::out /*| ios::binary*/ | ios::app); // ID, 이메일, 계정권한, 예약내역이 기록될 파일
        if (!userInfoFile) {
            cerr << "File could not be opened" << endl;
            exit(EXIT_FAILURE);
        }   // 파일스트림 부분의 코드를 깔끔하게 정리할 수 있는 방법은 뭘까요..

        if (inputPW() == true) {
            if (inputEmail() == true) {
                accountFile << getID() << endl;
                accountFile << cipher(getPW()) << endl; // 암호화하여 파일에 입력

                userInfoFile << getID() << endl;
                userInfoFile << getEmail() << endl;
                userInfoFile << getAuthInfo() << endl;
            }
        }
    }
    accountFile.close();
}
  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • try ~ catch ~ finally 구문을 사용해서 한번 정리해보세요.

    // 파일을 열고, 실패할 경우 예외를 던지는 식으로 함수를 하나 만듭니다. (대충 다음과 같을겁니다.)
    static void openFile(ofstream& os, char const * const filename) {
       os.open(filename,ios::out|ios::app);
        if (!os.is_open()) {
            throw string("File could not be opened");
        } 
    }
    
    void RegisterAccount::createAccount() {
      ofstream accountFile, userInfoFile;
      try {
        openFile(accountFile, "pass.dat")
    
        if (inputID() == true) {    // getID()에 userID가 들어오는 시점
    
            string fileNameToUserName = (getID() + ".dat"); 
            openFile(userInfoFile,fileNameToUserName.c_str());
            if (inputPW() == true) {
                if (inputEmail() == true) {
                    accountFile << getID() << endl;
                    accountFile << cipher(getPW()) << endl; // 암호화하여 파일에 입력
    
                    userInfoFile << getID() << endl;
                    userInfoFile << getEmail() << endl;
                    userInfoFile << getAuthInfo() << endl;
                }
            }
        }
      } catch(string err) {
        // 파일이 열리지 않았을 때, 예외 처리.
        // 필요한 경우, 예외정보를 저장하는 예외타입을 만들어도 좋습니다.
        cerr << err << endl;
        exit(EXIT_FAILURE);
      } finally {
        if(accountFile.is_open()) accountFile.close();
        if(userInfoFile.is_open()) userInfoFile.close();
      }
    }
    

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)