Project Hub

13. 파일 입출력 본문

C++/c++ basic

13. 파일 입출력

safy 2022. 12. 21. 14:13
728x90
반응형

이전 글

2022.12.21 - [C++/c++ basic] - 12. 입출력 (istream, ostream)

 

12. 입출력 (istream, ostream)

이전 글 2022.12.21 - [C++/c++ basic] - 11. virtual 함수와 다형성 11. virtual 함수와 다형성 이전 글 2022.12.21 - [C++/c++ basic] - 10. 업 캐스팅 & 다운 캐스팅 10. 업 캐스팅 & 다운 캐스팅 이전 글 2022.12.21 - [C++/c++ b

projecthub.tistory.com


ifstream

텍스트 파일을 읽는 가장 기본적인 예시다.

#include <iostream>
#include <fstream>
#include <string>
 
int main()
{
    std::ifstream in("C:\\Users\\seonjoo.kim\\Desktop\\123.txt");
    std::string s;
 
    if (in.is_open())
    {
        in >> s;
        std::cout << "입력 받은 문자열: " << s << std::endl;
    }
    else
    {
        std::cout << "파일을 찾을 수 없습니다." << s << std::endl;
    }
 
    in.close(); // 소멸자에서 자동적으로 호출.
    return 0;
}


파일 전체 읽기

위의 방식으로는 공백 문자 전까지 읽고 반환을 한다.

그래서 텍스트 파일의 처음부터 끝까지 읽기 위해서는 아래와 같은 방법을 사용하면 된다.

#include <iostream>
#include <fstream>
#include <string>
 
int main()
{
    std::ifstream in("C:\\Users\\seonjoo.kim\\Desktop\\123.txt");
    std::string s;
 
    if (in.is_open())
    {
        // 위치 지정자를 파일 끝으로 옮긴다.
        in.seekg(0, std::ios::end);
 
        // 그리고 그 위치를 읽는다.  (파일 크기)
        int size = in.tellg();
 
        // 그 크기의 문자열을 할당한다.
        s.resize(size);
 
        // 위치 지정자를 다시 파일 맨 앞으로 옮긴다.
        in.seekg(0, std::ios::beg);
 
        // 파일 전체 내용을 일겅서 문자열에 저장한다.
        in.read(&s[0], size);
        std::cout << s << std::endl;
    }
    else
    {
        std::cout << "파일을 찾을 수 없습니다." << std::endl;
    }
 
    return 0;
}


파일 전체를 한 줄씩 읽기

  • getline 함수를 사용하여 한줄씩 읽을 수 있다.
  • getline 함수는 파일에서 개행문자(\n) 가 나올 때 까지 최대 지정한 크기 - 1 만큼 읽게 된다. (널 종료 문자가 buf 에 들어가기 때문)
  • 원하는 문자가 나올 때 까지 읽는 것도 가능하다.
    • getline(buf, 100, '.');    => 마침표가 나올 때 까지 입력 받는다.
  •  아래 코드에서 주의해야 할 점은 while 문의 조건으로 in 을 전달해야 한다는 것이다.
  • in 이 true가 되기 위해서 다음 입력 작업이 성공적이어야 하고, 현재 스트림에 오류 플래그가 켜져 있지 않아야 한다.
  • getline 함수를 사용하기 전에 버퍼의 크기를 적절히 설정할 수 있도록 해야 한다.
#include <iostream>
#include <fstream>
#include <string>
 
int main()
{
    std::ifstream in("C:\\Users\\seonjoo.kim\\Desktop\\123.txt");
    char buf[100];
 
    if (!in.is_open())
    {
        std::cout << "파일을 찾을 수 없습니다." << std::endl;
    }
    else
    {
        while (in)
        {
            in.getline(buf, 100);
            std::cout << buf << std::endl;
        }
    }
 
    return 0;
}

위와 같이 ifstream 의 getline 을 활요할 때보다 훨씬 편하게 사용할 수 있도록 std::string 에 getline 함수가 정의되어 있다.

 

다음은 첫 번째 인자로 ifstream 객체를 받고, 두 번째 인자로 입력 받은 문자열을 저장할 string 객체를 받는다.

이 방법은 버퍼의 크기를 지정하지 않아도 되서 편리하다.

개행문자 혹은 파일의 끝이 나올 때 까지 입력받게 된다.

#include <iostream>
#include <fstream>
#include <string>
 
int main()
{
    std::ifstream in("C:\\Users\\seonjoo.kim\\Desktop\\123.txt");
    std::string s;
 
    if (!in.is_open())
    {
        std::cout << "파일을 찾을 수 없습니다." << std::endl;
    }
    else
    {
        while (in)
        {
            getline(in, s);
            std::cout << s << std::endl;
        }
    }
 
    return 0;
}


ofstream

파일에 쓰는 가장 기본적인 예시다.

경로에 파일이 존재하지 않을 경우, 파일을 생성하고, 파일에 출력함

 

파일이 존재한다면, 특별한 설정을 하지 않을 경우 해당 파일 내용이 다 지워지고 새로운 내용으로 덮어 씌어지게 된다.

#include <iostream>
#include <fstream>
#include <string>
 
int main()
{
    std::ofstream out("C:\\Users\\seonjoo.kim\\Desktop\\test.txt");
    std::string s;
 
    if (out.is_open())
    {
        out << "success!";
    }
 
    return 0;
}


옵션을 통해 뒤에 내용을 붙이기 위해서는 아래와 같이 하면 된다.

#include <iostream>
#include <fstream>
#include <string>
 
int main()
{
    std::ofstream out("C:\\Users\\seonjoo.kim\\Desktop\\test.txt", std:ios::app);
    std::string s;
 
    if (out.is_open())
    {
        out << "add string";
    }
 
    return 0;
}


문자열 스트림 (std::stringstream)

문자열을 하나의 스트림이라 생각하게 해주는 가상화 장치

#include <iostream>
#include <sstream>
 
int main()
{
    std::istringstream ss("123");
    int x;
 
    ss >> x;  // 문자열을 숫자로 변환
 
    std::cout << "입력 받은 데이터: " << x << std::endl;
 
    return 0;
}


이를 활용하면, atoi 와 같은 함수를 사용할 필요 없이 간편하게 문자열에서 숫자로 변환하는 함수를 만들 수 있다.

#include <iostream>
#include <sstream>
 
double to_number(std::string s)
{
    std::istringstream ss(s);
    double x;
 
    ss >> x;
 
    return x;
}
 
int main()
{
    std::cout << "변환 : 1 + 2 = " << to_number("1") + to_number("2") << std::endl;
 
    return 0;
}


반대로 숫자를 문자열로 변환하는 함수도 가능하다.

#include <iostream>
#include <sstream>
 
double to_str(int x)
{
    std::ostringstream ss;
    ss << x;
 
    return x.str();
}
 
int main()
{
    std::cout << "변환 : 1 + 2 = " << to_str(1 + 2) << std::endl;
 
    return 0;
}



728x90
반응형
Comments