일상 코딩
[C++/CPP] 18.06. basic file i/o 본문
728x90
#include<iostream>
#include<fstream> // file I/O library
#include<string>
#include<cstdlib>
#include<sstream>
using namespace std;
int main()
{
// writing
if(true)
{
ofstream ofs("my_first_file.dat", ios::binary); // ios::app - append mode, ios::binary
// ofs.open("my_first_file.dat")
if (!ofs)
{
cerr << "Couldn't open file " << endl;
exit(1);
}
// ASCII로 저장하는 line
// string st("Line ");
// for (int i = 1; i < 6; ++i)
// ofs << st + std::to_string(i) << endl;
// binary write
// 현업에선 binary만씀.
const unsigned num_data = 10;
ofs.write((char*)&num_data, sizeof(num_data));
for (int i = 0; i < num_data ; ++i)
ofs.write((char*)&i, sizeof(i));
}
// reading
if(true)
{
ifstream ifs("my_first_file.dat", ios::binary); //, ios::binary);
if(!ifs)
{
cerr << "Cannot open file" << endl;
exit(1);
}
// ASCII read
// while(ifs)
// {
// std::string str;
// getline(ifs, str);
// std::cout << str << endl;
// }
// binary read
unsigned num_data = 0;
ifs.read((char*)&num_data, sizeof(num_data));
for (unsigned i = 0; i < num_data; ++i)
{
int num;
ifs.read((char*)&num, sizeof(num));
cout << num << endl;
}
}
return 0;
}
728x90
'C++ > 따배C++ 18강 입력과 출력' 카테고리의 다른 글
[C++/CPP] 18.07. Random Accessing File, read / write (0) | 2021.12.22 |
---|---|
[C++/CPP] 18.05 regular expressions, 정규 표현식 (0) | 2021.12.19 |
[C++/CPP] 18.04. stream states, input validation (0) | 2021.12.19 |
[C++/CPP] 18.03. 문자열 stream (0) | 2021.12.18 |
[C++/CPP] 18.02. ostream output (0) | 2021.12.17 |