CodeLabs

[C++] .txt 파일 읽기와 쓰기 본문

C++

[C++] .txt 파일 읽기와 쓰기

무오_ 2023. 7. 6. 18:09

( 솔루션 우클릭 - 파일 탐색기에서 폴더 열기 - 프로젝트 이름으로 된 폴더로 이동 - 파일 생성 )

우클릭

 

 

파일 상태

#include <iostream>
#include <fstream> // ifstream, ofstream
#include <string>  // getline

using namespace std;

int main()
{
	string inputFileName = "읽기 파일.txt";
	string outputFileName = "쓰기 파일.txt";

	// 파일이름.txt (확장자까지)
	ifstream inputFile(inputFileName);
	ofstream outputFile(outputFileName);

	// 파일이 제대로 열렸는지 확인하는 작업
	if (!inputFile.is_open())
	{
		cout << "\"" << inputFileName << "\"이 제대로 열리지 않음" << endl;
		cout << "파일 이름을 다시 확인하세요." << endl;
		return 1;
	}

	if (!outputFile.is_open())
	{
		cout << "\"" << outputFileName << "\"이 제대로 열리지 않음" << endl;
		cout << "파일 이름을 다시 확인하세요." << endl;
		return 1;
	}

	string line;
	// 읽기 파일에서 한줄씩 읽어서 line 변수에 저장
	while (getline(inputFile, line))
	{
		// 쓰기 파일에 값을 저장
		outputFile << stoi(line) * 10 << endl;
	}

	// 파일의 사용이 끝났으면 꼭 닫아주기
	inputFile.close();
	outputFile.close();

	return 0;
}

 

 

결과

'C++' 카테고리의 다른 글

[C++] 입력과 출력  (0) 2023.06.30
[C/C++] 포인터(*) 사용법  (0) 2023.06.22