C++ 파일
C++ 파일
fstream
라이브러리를 사용하면 파일 작업을 할 수 있습니다 .
fstream
라이브러리 를 사용하려면 표준 <iostream>
및<fstream>
헤더 파일 을 모두 포함 합니다 .
예시
#include <iostream>
#include <fstream>
fstream
라이브러리에는 파일 생성, 쓰기 또는 읽기에 사용되는 세 가지 클래스가 포함되어 있습니다.
Class | Description |
---|---|
ofstream |
Creates and writes to files |
ifstream |
Reads from files |
fstream |
A combination of ofstream and ifstream: creates, reads, and writes to files |
파일 생성 및 쓰기
파일을 생성하려면 ofstream
또는 fstream
클래스를 사용하고 파일 이름을 지정합니다.
파일에 쓰려면 삽입 연산자( <<
)를 사용합니다.
예시
#include <iostream>
#include <fstream>
using namespace std;
int main() {
// Create and open a text file
ofstream MyFile("filename.txt");
//
Write to the file
MyFile << "Files can be tricky, but it is fun
enough!";
//
Close the file
MyFile.close();
}
파일을 닫는 이유는 무엇입니까?
이는 좋은 습관으로 간주되며 불필요한 메모리 공간을 정리할 수 있습니다.
파일 읽기
파일에서 읽으려면 ifstream
또는 fstream
클래스와 파일 이름을 사용하십시오.
파일을 한 줄씩 읽고 파일 내용을 인쇄하기 위해 (클래스 에 속한) 함수 while
와 함께 루프 를 사용한다는 점에 유의 하십시오.getline()
ifstream
예시
// Create a
text string, which is used to output the text file
string myText;
// Read from the text file
ifstream MyReadFile("filename.txt");
// Use a while
loop together with the getline() function to read the file line by line
while (getline (MyReadFile,
myText)) {
// Output the text from the file
cout << myText;
}
// Close the file
MyReadFile.close();