http://www.prglab.com/cms/pages/c-tutorial/file-inputoutput.php
#include <fstream>
TEXT I/O
ofstream output;
output.open("output.txt");
// some operation
output.close(); // close the file
TEST FILE EXISTENCE
input.fail()
TEST EOF
while(!input.eof()) {
input >> number;
if(input.eof()) break;
// operation
}
// or
while(input >> number){
// operation
}
FORMATTING OUTPUT
#include <iomanip>
// ...
output << setw(6) << str << endl;
GETLINE, GET, PUT
getline(input, str, '\n');
ch = input.get();
input.get(ch);
output.put(ch);
FILE OPEN MODES
- ios::in
为输入(读)而打开文件 - ios::out
为输出(写)而打开文件 - ios::ate
初始位置:文件尾 - ios::app
所有输出附加在文件末尾 - ios::trunc
如果文件已存在则先删除该文件 - ios::binary
二进制方式
这些方式是能够进行组合使用的,以“或”运算(“|”)的方式:例如
ofstream out;
out.open("Hello.txt", ios::in|ios::out|ios::binary);
TESTING STREAM STATE
- eof()
- fail()
- bad()
- good()
- clear()
BINARY I/O
WRITE
fstream binaryio("city.dat", ios::out | ios::binary);
string s = "Atlanta";
binaryio.write(s.c_str(), s.size());
int value = 199;
binaryio.write(reinterpret_cast<char*>(&value), sizeof(value));
// Simply performing a binary copy of the value without altering the data, not converting int to char
binaryio.close();
READ
fstream binaryio("city.dat", ios::in | ios::binary);
char s[10];
binaryio.read(s, 10);
int value;
binaryio.read(reinterpret_cast<char*>(&value), sizeof(value));
binary.close();
RANDOM ACCESS FILE
- seekg()
- seekp()
Student StudentNew;
binaryio.seekg(2 * sizeof(Student));// move to third Student
binaryio.read(reinterpret_cast<char*>(&StudentNew), sizeof(Student));