C++에서 파일 생성, 쓰기 및 읽기 방법은 무엇인가요?
파일을 생성하고 쓰고 읽는 것은 C++ 프로그래밍에서 중요한 부분입니다. 다음은 파일을 생성하고 쓰고 읽는 방법입니다.
파일 생성
파일을 생성하려면 ofstream
클래스를 사용합니다. 다음은 파일을 생성하는 예제입니다.
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt");
return 0;
}
위의 코드는 example.txt
라는 파일을 생성합니다. 파일이 이미 존재하는 경우, 해당 파일이 열리고 파일의 내용이 지워집니다.
파일 쓰기
파일에 쓰려면 <<
연산자를 사용하여 ofstream
객체에 데이터를 씁니다. 다음은 파일에 문자열을 쓰는 예제입니다.
#include <fstream>
using namespace std;
int main() {
ofstream file("example.txt");
file << "Hello, World!";
file.close();
return 0;
}
위의 코드는 example.txt
파일에 "Hello, World!"라는 문자열을 씁니다. close()
함수를 호출하여 파일을 닫습니다.
파일 읽기
파일을 읽으려면 ifstream
클래스를 사용합니다. 다음은 파일에서 문자열을 읽는 예제입니다.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
ifstream file("example.txt");
string str;
getline(file, str);
cout << str << endl;
file.close();
return 0;
}
위의 코드는 example.txt
파일에서 한 줄을 읽어 str
변수에 저장하고 출력합니다. close()
함수를 호출하여 파일을 닫습니다.
이외에도 fstream
클래스를 사용하여 파일을 생성, 쓰기 및 읽기를 모두 수행할 수 있습니다. 다음은 fstream
클래스를 사용하여 파일을 생성하고 쓰는 예제입니다.
#include <fstream>
#include <iostream>
using namespace std;
int main() {
fstream file("example.txt", ios::out);
file << "Hello, World!";
file.close();
return 0;
}
위의 코드는 example.txt
파일을 생성하고 "Hello, World!"라는 문자열을 씁니다. ios::out
플래그를 사용하여 파일을 쓰기 모드로 엽니다.