// default (1) fstream();// initialization (2) explicitfstream(constchar*filename,ios_base::openmodemode=ios_base::in|ios_base::out);// filename : 파일의 이름을 나타내는 문자열// mode : 파일에 대해 요청된 입/출력 모드 플래그
mode
member constant
stands for
access
in
input
File open for reading: the internal stream buffer supports input operations.
out
output
File open for writing: the internal stream buffer supports output operations.
binary
binary
Operations are performed in binary mode rather than text.
ate
at end
The output position starts at the end of the file.
app
append
All output operations happen at the end of the file, appending to its existing contents.
trunc
truncate
Any contents that existed in the file before it is open are discarded.
스트림에서 문자를 추출한다. n개의 문자가 s에 기록될 때까지 s에 c-string으로 저장한다.
구분 문자는 개행 문자(\n)이거나 지정된 문자(delim)이다.
1
2
3
4
5
6
istream&getline(char*s,streamsizen);istream&getline(char*s,streamsizen,chardelim);// s : 추출된 문자 배열의 포인터// n : 읽을 문자의 최대 개수// delim : 명시적 구분 문자로서 이 문자가 발견되면 추출 작업 종료
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// istream::getline example#include <iostream> // std::cin, std::cout
intmain(){charname[256],title[256];std::cout<<"Please, enter your name: ";std::cin.getline(name,256);std::cout<<"Please, enter your favourite movie: ";std::cin.getline(title,256);std::cout<<name<<"'s favourite movie is "<<title;return0;}
ostream
write : 데이터 쓰기
문자열 앞에서부터 n개의 문자를 스트림에 넣는다.
1
2
3
4
5
ostream&write(constchar*s,streamsizen);// s : 최소 n개의 문자를 가진 문자열// n : 삽입할 문자의 개수// 반환 : ostream 개체
// Copy a file#include <fstream> // std::ifstream, std::ofstream
intmain(){std::ifstreaminfile("test.txt",std::ifstream::binary);std::ofstreamoutfile("new.txt",std::ofstream::binary);// get size of fileinfile.seekg(0,infile.end);longsize=infile.tellg();infile.seekg(0);// allocate memory for file contentchar*buffer=newchar[size];// read content of infileinfile.read(buffer,size);// write to outfileoutfile.write(buffer,size);// release dynamically-allocated memorydelete[]buffer;outfile.close();infile.close();return0;}
c++ fstream
[파일 입출력에 대해서](https://blockdmask.tistory.com/322