파일 입출력 클래스는 fstream 클래스에 있다.
클래스의 open()메소드를 통해 파일을 열거나 생성할 수 있다.
파일을 닫을 때는 close()를 호출하여 명시적으로 파일을 닫을 수 있다.
파일을 읽어들이는 방법으로는 한글자씩 읽어들이는 방법(get), 한줄씩 읽어들이는 방법(getline), 끝이 날때까지 읽어들이는 방법(!readFile.eof()) 등이 있다.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
//파일 쓰기
ofstream writeFile;
writeFile.open("test.txt");
char str[256] = "wonderful world";
writeFile.write(str, strlen(str));
writeFile.close();
ifstream readFile;
readFile.open("test.txt");
//파일이 열리면
if (readFile.is_open()) {
char str[256];
char c = readFile.get(); //한글자씩읽어들여
cout << c << endl;
readFile.getline(str, 256);
cout << str << endl;
}
//파일이 열리면
if (readFile.is_open()) {
char c;
while (readFile.get(c)) { //파일의 끝이 아니면
cout << c;
}
}
//파일이 열리면
if (readFile.is_open()) {
while (!readFile.eof()) { //파일의 끝이 아니면
char str[256];
readFile.getline(str, 256);
cout << str << endl;
}
}
readFile.close();
return 0;
}

'C++' 카테고리의 다른 글
09. C++_동적으로 배열 할당하기 (0) | 2024.05.16 |
---|---|
07. C++_call by value/call by pointer/ call by reference 이해하기 (0) | 2024.05.16 |
04. C++_얕은복사/깊은복사 (1) | 2024.03.24 |
03. C++_invoke (0) | 2024.03.24 |
02. C++_Initializer_list (1) | 2024.03.18 |