[C++] 파일 입출력
Updated:
예제
- 코드
#include <fstream> #include <iostream> #include <string> using namespace std; void read(string fileName) { ifstream is(fileName.c_str()); is.seekg(0, is.end); long size = is.tellg(); is.seekg(0); char buffer[size]; if (is.read(buffer, size)) { cout << "read ok" << endl; cout << "------" << endl; cout << buffer << endl; cout << "------" << endl; } else { cout << "read fail" << endl; } } void write(string fileName, string buffer) { ofstream os(fileName.c_str(), ofstream::trunc); if (os.write(buffer.c_str(), buffer.size())) { cout << "write ok" << endl; } else { cout << "write fail" << endl; } } int main() { string fileName = "./test.txt"; string buffer = "abc"; write(fileName, buffer); read(fileName); return 0; }
- 실행 결과
write ok read ok ------ abc ------