C++中文件流(fstream)的使用方法及示例

来源:互联网 发布:思迅软件合作伙伴社区 编辑:程序博客网 时间:2024/05/21 22:41

C++文件流:

[cpp] view plain copy
  1. fstream  // 文件流  
  2. ifstream  // 输入文件流  
  3. ofstream  // 输出文件流  

 

 

[cpp] view plain copy
  1. #include <fstream>  
  2.   
  3. //创建一个文本文件并写入信息  
  4. //同向屏幕上输出信息一样将信息输出至文件  
  5. #include<iomanip.h>  
  6. #include<fstream>  
  7.   
  8. void main()  
  9. {  
  10. ofstream ofs("C:\\example.txt");           //打开文件用于写,若文件不存在就创建它  
  11. if (!ofs) return;                  //打开文件失败则结束运行  
  12.   
  13. f1 << setw(20) << "Name: " << "Beethoven" << endl;     //使用插入运算符写文件内容  
  14. f1 << setw(20) << "song: " << "Moonlight Sonata" << endl;  
  15. f1.close();                   //关闭文件  
  16. }  



文件操作:
打开文件

文件名
注意路径名中的斜杠要双写,如:
"D:\\MyFiles\\ReadMe.txt"

文件打开方式选项:

[cpp] view plain copy
  1. ios::in    = 0x01, //供读,文件不存在则创建(ifstream默认的打开方 式)  
  2. ios::out    = 0x02, //供写,文件不存在则创 建,若文件已存在则清空原内容(ofstream默认的打开方式)  
  3. ios::ate    = 0x04, //文件打开时,指针在文件最后。可改变指针的位置,常和in、out联合使用  
  4. ios::app    = 0x08, //供写,文件不存在则创建,若文件已存在则在原文件内容后写入 新的内容,指针位置总在最后  
  5. ios::trunc   = 0x10, // 在读写前先将文件长度截断为0(默认)  
  6. ios::nocreate = 0x20, //文件不存在时产生错误,常和in或app联合使用  
  7. ios::noreplace = 0x40, //文件存在时产生错误,常和out联合使用  
  8. ios::binary  = 0x80  //二进制格式文件  


文件保护方式选择项:

[cpp] view plain copy
  1. filebuf::openprot;   //默认的兼容共享方式  
  2. filebuf::sh_none;    //独占,不共享  
  3. filebuf::sh_read;    //读共享  
  4. filebuf::sh_write;   //写共享  


打开文件的方法
调用构造函数时指定文件名和打开模式

[cpp] view plain copy
  1. ifstream f("d:\\12.txt", ios::nocreate);         //默认以 ios::in 的方式打开文件,文件不存在时操作失败  
  2. ofstream f("d:\\12.txt");                //默认以 ios::out的方式打开文件  
  3. fstream  f("d:\\12.dat", ios::in|ios::out|ios::binary); //以读 写方式打开二进制文件  


使用Open成员函数

[cpp] view plain copy
  1. fstream f;  
  2. f.open("d:\\12.txt",ios::out);             //利用同一对象对多个文件进行操作时要用到open函数  



检查是否成功打开
成功:

[cpp] view plain copy
  1. if (f) {...}       //对ifstream、ofstream对象可 用,fstream对象不可用。 mysql  
  2. if (f.good()) {...}  


失败:

[cpp] view plain copy
  1. if (!f) {...}       // !运算符已经重载  
  2. if (f.fail()) {...}  

 

读写操作
使 用<<,>>运算符
只能进行文本文件的读写操作,用于二进制文件可能会产生错误。
使用函数成员 get、put、read、write等
经常和read配合使用的函数是 gcount(),用来获得实际读取的字节数。

读写二进制文件注意事项
打开方式中必须指定ios::binary,否则读写会出错
用read\write进行读写操作,而不能使用插入、提取运算符进行操作,否则 会出错。
使用eof()函数检测文件是否读结束,使用gcount()获得实际读取的字节数

关闭文件
使用成员函数close, 如: oracle
f.close(); 
利用析构函数
对象生命期结 束时会检查文件是否关闭,对没有关闭的文件进行关闭操作。

随机读写文件
通过移动文件读写指针,可在文件指定位置进行读写。

[cpp] view plain copy
  1. seekg(绝对位置);      //绝对移动,    //输入流操作  
  2. seekg(相对位置,参照位置);  //相对操作  
  3. tellg();          //返回当前指针位置  
  4. seekp(绝对位置);      //绝对移动,    //输出流操作  
  5. seekp(相对位置,参照位置);  //相对操作     
  6. tellp();          //返回当前指针位置  


参照位置: mysql

[html] view plain copy
  1. ios::beg  = 0       //相对于文件头  
  2. ios::cur   = 1       //相对于当前位置  
  3. ios::end  = 2       //相对于文件尾  

 

 写文本文件的示例
//为能够正确读出写入文件的各数据,各数据间最好要有分隔

[html] view plain copy
  1. #include<fstream>  
  2.   
  3. void main()  
  4. {  
  5. fstream f("d:\\try.txt", ios::out);  
  6. << 1234 << ' ' << 3.14 << 'A' << "How are you"; //写入数据  
  7. f.close();  
  8. f.open("d:\\try.txt", ios::in);  
  9. int i;  
  10. double d;  
  11. char c;  
  12. char s[20];  
  13. >> i >> d >> c;               //读取数据  
  14. f.getline(s,20);  
  15. cout << i << endl;             //显示各数据  
  16. cout <<d << endl;  
  17. cout << c << endl;  
  18. cout << s << endl;  
  19. f.close();  
  20. }  


运 行结果:
1234
3.14
A
How are you
Press any key to continue

显示文本文件的内容

[html] view plain copy
  1. //使用get()一次读一个字符--------------------------------方案一  
  2. #include<fstream>  
  3.   
  4.   
  5. void main()  
  6. {  
  7. ifstream fin("d:\\简介.txt", ios::nocreate);  
  8. if (!fin) {  
  9. cout << "File open error!\n";  
  10. return;  
  11. }  
  12. char c;  
  13. while ((c=fin.get()) != EOF) cout << c;    //注意结束条件的判断  
  14. fin.close();  
  15. }  


//使用get(char *,int n,char delim='\n')一次读多个字符----方案二
//巧妙利用文本文件中不会有字符'\0'的特点进行读取

[cpp] view plain copy
  1. #include<fstream>  
  2. void main()  
  3. {  
  4. ifstream fin("d:\\简介.txt",ios::nocreate);  
  5. if(!fin){  
  6. cout<<"File open error!\n";  
  7. return;  
  8. }  
  9. char c[80];  
  10. while(fin.get(c,80,'\0')!=NULL)cout<<c; //注意结束条件的判断  
  11. fin.close();  
  12. }  
  13. //使用read(char *,int n)读文件---------------------------方案三  
  14. #include<fstream.h>  
  15. void main()  
  16. {  
  17. ifstream fin("d:\\简介.txt",ios::nocreate);  
  18. if(!fin){  
  19. cout<<"File open error!\n";  
  20. return;  
  21. }  
  22. char c[80];  
  23. while(!fin.eof())            //判 断文件是否读结束  
  24. {  
  25. fin.read(c,80);  
  26. cout.write(c,fin.gcount());  
  27. }  
  28. fin.close();  
  29. }  


 

拷贝文件
//二进制文件操作示例 ssh

[cpp] view plain copy
  1. #include<fstream>  
  2.   
  3. void main()  
  4. {  
  5. ifstream fin("C:\\1.exe", ios::nocreate|ios::binary);  
  6. if (!fin) {  
  7. cout << "File open error!\n";  
  8. return;  
  9. }  
  10. ofstream fout("C:\\2.exe", ios::binary);  
  11. char c[1024];  
  12. while (!fin.eof())  
  13. {  
  14. fin.read(c, 1024);  
  15. fout.write(c, fin.gcount());  
  16. }  
  17. fin.close();  
  18. fout.close();  
  19. cout << "Copy over!\n";  
  20. }  


 一个打开并检查输入文件的程序:

[cpp] view plain copy
  1. #include<iostream>  
  2. #include<fstream>  
  3. #include<string>  
  4. using namespace std;  
  5. ifstream& open_file(ifstream &in,const string &file)  
  6. {  
  7.     in.close();  
  8.     in.clear();  
  9.     in.open(file.c_str());  
  10.     return in;  
  11. }  
  12. int main()  
  13. {  
  14.     ifstream file;  
  15.     open_file(file,"1.txt");  
  16.     string s;  
  17.     while(getline(file,s))  
  18.     {  
  19.         cout<<s<<endl;  
  20.     }  
  21.     file.close();  
  22.     return 0;  
  23. }  
0 0