1.向文件写数据
头文件#include <ofstream>
①Create an instance of ofstream(创建ofstream实例)
②Open the file with open() or ofstreamconstructor (用open()或者构造函数打开文件)
③Writedata to the file with "<<" (用流插入运算符写数据)
④Close the file (explicitly close()) (显式地使用close()函数关闭文件)
若文件已存在,内容被直接清除。
1 #include <iostream> 2 #include <fstream> 3 using namespace std; 4 5 int main() 6 { 7 // ofstream output("score.txt"); 构造函数打开文件 8 ofstream output; 9 //创建文件 10 output.open("score.txt"); 11 //写数据 output 类似于cout 12 output << "daidai" << " " << 90 << endl; 13 //关闭文件 14 output.close(); 15 return 0; 16 }
2.从文件读数据
头文件#include <ifstream>
①Create an instance of ifstream(创建ifstream对象)
②Open the file (use open() or ifstreamconstructor) (用open()函数或构造函数打开文件)
③Read data from the file with ">>" (用流提取运算符从文件读数据)
④Close the file (explicitly using close() ) (显式调用close()函数关闭文件)
1 #include <iostream> 2 #include <fstream> 3 using namespace std; 4 5 int main() 6 { 7 // ofstream output("score.txt"); 构造函数打开文件 8 ifstream input; 9 //打开文件 10 input.open("score.txt"); 11 //读数据 input 12 char name[80]; 13 int score; 14 input >> name >> score; 15 cout << name << " " << score << endl; 16 //关闭文件 17 input.close(); 18 return 0; 19 }
3.格式控制
头文件#include <iomanip>
①setw(width) 设置域宽
setw()控制符只对其后输出的第一个数据有效,其他控制符则对其后的所有输入输出产生影响。
默认为setw(0),按实际输出。
如果输出的数值占用的宽度超过setw(int n)设置的宽度,则按实际宽度输出。
Eg: cout<<setw(5)<<'a'<<'b'<<endl; 输出: ab
float f=0.12345; cout<<setw(3)<<f<<endl; 输出为0.12345
②setfill(c)
设置填充字符,即“<<"符号后面的数据长度小于域宽时,使用什么字符进行填充。
Eg: cout<<setfill('*')<<setw(5)<<'a'<<endl; 输出:****a
③setprecision(int n)
可以控制显示浮点数的有效位
n代表数字总位数
setprecision(0)的效果取决于编译器。不同编译器的实现是不同的。
本例中:
VC++2013输出:2.42857
Dev C++ 5.6.0 (MinGW GCC 4.8.1)输出: 2
④showpoint
将浮点数以带小数点、带结尾0 的形式输出,即便它没有小数部分
Eg:
float f1 = 13;
float f2 = 3.1415926;
float f3 = 5;
cout << showpoint << f1 << endl;
cout << showpoint << f2 << " " << f3 <<endl;
输出:13.0000
3.14159 5.00000
⑤left 输出内容左对齐
right 输出内容右对齐
Eg:
cout << setw(5) << 13 << endl;
cout << setw(5) << right << 13 << endl;
cout << setw(5) << left << 13 << endl;
输出: 13
13
13
⑥getline
getline(chararray[], intsize, chardelimitChar) //要写入的数组,大小,分隔符
因为 >>运算符要求数据用空格分隔
1 #include <iostream> 2 #include <fstream> 3 using namespace std; 4 int main() 5 { 6 ifstream input("state.txt"); 7 char name[30]; 8 input >> name; 9 cout << name << endl; 10 return 0; 11 }
与预期不同。
1 //运用getline 2 #include <iostream> 3 #include <fstream> 4 using namespace std; 5 int main() 6 { 7 ifstream input("state.txt"); 8 char name[30]; 9 while(!input.eof()){ // Continue if not end of file 10 input.getline(name,40,'#'); 11 cout << name << endl; 12 } 13 return 0; 14 }
⑦ get: read a character
put:write a character
1 //copy get put 2 #include <iostream> 3 #include <fstream> 4 using namespace std; 5 int main() 6 { 7 cout << "Enter a source file name:"; 8 char inputFilename[20]; 9 cin >> inputFilename; 10 11 cout << "Enter a target file name:"; 12 char outputFilename[20]; 13 cin >> outputFilename; 14 15 ifstream input(inputFilename); 16 ofstream output(outputFilename); 17 18 while( !input.eof() ) { //Continue if not end of file 19 output.put(input.get()); 20 } 21 22 input.close(); 23 output.close(); 24 cout << " Copy Done" << endl; 25 return 0; 26 }
4.文件打开模式
fstream= ofstream+ ifstream
ofstream: write data
ifstream: read data
Mode Description
ios::in Opens a file for input. 读模式
ios::out Opens a file for output. 写模式
ios::app Appends all output to the end of the file. 追加模式
ios::ate Opens a file for output. If the file already exists, move to the end of the file. Data can be written anywhere in the file.
打开文件用于输出。若文件存在则光标移至文件尾部。数据可以在任意位置写入
ios::truct Discards the file’s contents if the file already exists. (This is the default action for ios:out).
若文件存在则丢弃其内容,这是ios:out的默认方式
ios::binary Opens a file for binary input and output.打开文件以二进制模式读写
模式组合: |
Eg:stream.open("state.txt", ios::out | ios::app);
5.测试流状态
流状态位 (Stream State Bit):These bit values (0or 1) indicate the state of a stream. (比特值指示流的当前状态)
Bit When to set
ios::eofbit Set when the end of an input stream is reached. 到达文件末尾时
ios::failbit Set when an operation failed. 操作失败时
ios::hardfail Set when an unrecoverable error occurred. 遇到不可恢复的错误时
ios::badbit Set when an invalid operation has been attempted. 试图进行非法操作时
ios::goodbit Set when an operation is successful. 操作成功时
流状态函数(Stream State Functions)
Function Description
eof() Returns true if the eofbit flag is set.
fail() Returns true if the failbit or hardfail flags is set.
bad() Returns true if the badbit is set.
good() Returns true if the goodbit is set.
clear() Clears all flags.
6.二进制读写
文本文件与二进制文件,都按二进制格式存储比特序列
text file : interpretedas a sequence of characters (解释为一系列字符)
binary file : interpretedas a sequence of bits. (解释为一系列比特)
Eg: the decimal integer 199 (对于十进制整数199)
in text file: as the sequence of three characters, '1', '9', '9', (在文本文件中存为3个字符),stores as 3 bytes: 0x31, 0x39, 0x39 (三个字符的ASCII码)
in bin file: as a byte-type value C7(decimal 199= hex C7 (在二进制文件中存为C7),stores as 1 bytes: 0xC7
ios::binary以二进制模式打开文件
文本模式读写函数
write: <<operator; put()
read : >>operator; get(); getline()
二进制模式读写函数
write: write(); streamObject.write(char* address, intsize)
read : read(); streamObject.read(char * address, intsize)
将任意类型数据写入文件:转换为字节流,write进去。
reinterpret_cast<dataType>(address) //将数据的地址转换为为字符类型指针用于二进制读写
Eg:streamObject.write(reinterpret_cast<char *>, intsize);
char s[10]; streamObject.read(s, intsize);
int value; streamObject.read(reinterpret_cast<char*>(&value), sizeof(value));
double array[] = {1.1,2.2,3.3} streamObject.write(reinterpret_cast<char*>(array), sizeof(array));
Student stu1("kuotian",20,'f'), stu2;
streamObject.write(reinterpret_cast<char*>(&stu1), sizeof(Student));
streamObject.read(reinterpret_cast<char*>(&stu2), sizeof(Student));
7.
seekp, seekg, tellp, tellg
seek: 移动文件指针
tell:获取文件指针位置
p: put,表示操作输出文件中的指针
g: get,表示操作输入文件中的指针
Seek Base Description
ios::beg Calculates the offset from the beginning of the file.
ios::end Calculates the offset from the end of the file.
ios::cur Calculates the offset from the current file pointer.
Statement Description
seekg(100L, ios::beg); Moves the file pointer to the 100th byte from the beginning of the file.
seekg(-100L, ios::end); Moves the file pointer to the 100th byte backward from the end of the file.
seekp(42L, ios::cur); Moves the file pointer to the 42nd byte forward from the current file pointer.
seekp(-42L, ios::cur); Moves the file pointer to the 42nd byte backward from the current file pointer.
seekp(100L); Moves the file pointer to the 100th byte in the file.