fstream的操作

第一段转载自:https://blog.csdn.net/jaster_wisdom/article/details/52400059

在C++中输入输出到指定文件,或者从指定文件中读出数据使用fstream类较为方便。

1.将数据写到磁盘的指定文件中

首先第一步是加头文件#include <fstream>,引入库函数

第二步,声明一个ofstream对象,调用ofstream的成员函数open函数,与指定的文件相关联

第三步,使用<<向文件中写入数据,注意<<操作符已经在库函数里重载过,所以直接调用即可。

最后一步,关闭输出流,调用close()函数


    
    
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. int main(){
  5. ofstream outfile;
  6. outfile.open( “D:\\data.txt”);
  7. outfile<< “随机产生的序列:”<< endl;
  8. for( int i= 0;i< 10;i++){
  9. outfile<<i<< endl;
  10. }
  11. outfile.close();
  12. return 0;
  13. }

在D盘data.txt文件中,应该是这样的效果:


注意,这里的data.txt文件可以提前创建,当然也可以有程序自动创建,也就是说当程序执行到该步时,发现该目录下没有该文件,那么会自动地生成一个文本文件。

在这里有时候会出现这样的问题,当我的代码是这样的:


    
    
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. int main(){
  5. ofstream outfile;
  6. outfile.open( "D:\\data.txt");
  7. outfile<< "随机产生的序列:"<< endl;
  8. for( int i= 0;i< 10;i++){
  9. outfile<<i<< " "; //注意这行与上面的区别
  10. }
  11. outfile.close();
  12. return 0;
  13. }

本意是想将数字横着输出一行,那么到底有没有实现这样的功能呢?

这里要分情况,如果是Dev或者其他比较流行的编译器,是没有任何问题的,效果如下:


但如果是Microsoft visual 6.0这种比较老式的编译器,就会出现这样的情况:


很明显,数字不见了。在此声明,这种情况只会在比较老式的编译器中出现。

原因是要写入的数据在缓冲区内,还没有保存到文本中,解决办法是写完之后刷新一次,调用flush()函数来清空缓冲区。


    
    
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. int main(){
  5. ofstream outfile;
  6. outfile.open( "D:\\data.txt");
  7. outfile<< "随机产生的序列:"<< endl;
  8. for( int i= 0;i< 10;i++){
  9. outfile<<i<< " "; //注意这行与上面的区别
  10. }
  11. outfile.flush();
  12. outfile.close();
  13. return 0;
  14. }
这里需要说明一下原理:

当程序向输出设备中输出数据时,输出的数据先被存放在计算机缓冲区(Buffer)内。当缓冲区存满时,这些数据才真正地输出到输出设备。但是,如果输出的字符序列中出现了endl控制符,那么缓冲区内的所有数据将立即输出到输出设备,而无论缓冲区是否已经存满。因此,endl的作用将光标移动到输出设备中下一行开头处,并且清空缓冲区。
很有可能,出现在程序终止时,并没有输出所有的输出数据的情况。这是因为在程序终止时,缓冲区不一定是满的,所有也就没有将缓冲区的数据写到输出设备。
在C++中,可以使用flush函数来清空缓冲区,即使缓冲区中的数据不是满的。


2.将磁盘文件中的数据读到控制台

原理和写到文件类似,就是一个逆过程。


    
    
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. int main(){
  5. ifstream infile;
  6. infile.open( "D:\\data.txt");
  7. string str;
  8. infile >> str;
  9. cout<<str<< endl;
  10. infile.close();
  11. return 0;
  12. }



            </div>

以下文章转载于:https://blog.csdn.net/seadplus/article/details/7802346









1
2
3

fstream   // 文件流  
ifstream  // 输入文件流  
ofstream  // 输出文件流





    <div id="crayon-5b6047e19c6d1302840318" class="crayon-syntax crayon-theme-github crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style="margin-top: 12px; margin-bottom: 12px; font-size: 13px !important; line-height: 15px !important; height: auto;">

        <div class="crayon-toolbar" data-settings=" show" style="font-size: 13px !important;height: 19.5px !important; line-height: 19.5px !important;"><span class="crayon-title"></span>
        <div class="crayon-tools" style="font-size: 13px !important;height: 19.5px !important; line-height: 19.5px !important;"><div class="crayon-button crayon-nums-button crayon-pressed" title="切换是否显示行编号"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-plain-button" title="纯文本显示代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-wrap-button" title="切换自动换行"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-expand-button" title="点击展开代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-copy-button" title="复制代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-popup-button" title="在新窗口中显示代码"><div class="crayon-button-icon"></div></div></div></div>
        <div class="crayon-info" style="min-height: 18.2px !important; line-height: 18.2px !important; margin-top: -18px; display: none;"></div>
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 13px !important; line-height: 15px !important; z-index: 0; opacity: 0;">#include &lt;fstream&gt;  

//创建一个文本文件并写入信息
//同向屏幕上输出信息一样将信息输出至文件

include<iomanip.h>

include<fstream>

void main()
{
ofstream ofs(“C:\example.txt”);           //打开文件用于写,若文件不存在就创建它
if (!ofs) return;                  //打开文件失败则结束运行

f1 << setw(20) << “Name: ” << “Beethoven” << endl;     //使用插入运算符写文件内容
f1 << setw(20) << “song: ” << “Moonlight Sonata” << endl;
f1.close();                   //关闭文件
}








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

#include <fstream>  
  
//创建一个文本文件并写入信息  
//同向屏幕上输出信息一样将信息输出至文件  
#include<iomanip.h>  
#include<fstream>  
  
void main ( )   
{   
ofstream ofs ( “C:\example.txt” ) ;            //打开文件用于写,若文件不存在就创建它  
if ( ! ofs ) return ;                   //打开文件失败则结束运行  
  
f1 << setw ( 20 ) << “Name: “ << “Beethoven” << endl ;     //使用插入运算符写文件内容  
f1 << setw ( 20 ) << “song: “ << “Moonlight Sonata” << endl ;   
f1 . close ( ) ;                   //关闭文件  
}





文件操作:

打开文件

文件名

注意路径名中的斜杠要双写,如:

“D:\\MyFiles\\ReadMe.txt”

文件打开方式选项:

文件保护方式选择项:

打开文件的方法

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

使用Open成员函数

检查是否成功打开

成功:

失败:

读写操作

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

读写二进制文件注意事项

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

关闭文件

使用成员函数close, 如: oracle

f.close();

利用析构函数

对象生命期结 束时会检查文件是否关闭,对没有关闭的文件进行关闭操作。

随机读写文件

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

参照位置: mysql

写文本文件的示例

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

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

显示文本文件的内容

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

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

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

拷贝文件

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

    <div id="crayon-5b6047e19c6ff992131461" class="crayon-syntax crayon-theme-github crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style="margin-top: 12px; margin-bottom: 12px; font-size: 13px !important; line-height: 15px !important; height: auto;">

        <div class="crayon-toolbar" data-settings=" show" style="font-size: 13px !important;height: 19.5px !important; line-height: 19.5px !important;"><span class="crayon-title"></span>
        <div class="crayon-tools" style="font-size: 13px !important;height: 19.5px !important; line-height: 19.5px !important;"><div class="crayon-button crayon-nums-button crayon-pressed" title="切换是否显示行编号"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-plain-button" title="纯文本显示代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-wrap-button" title="切换自动换行"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-expand-button" title="点击展开代码" style="display: none;"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-copy-button" title="复制代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-popup-button" title="在新窗口中显示代码"><div class="crayon-button-icon"></div></div></div></div>
        <div class="crayon-info" style="min-height: 18.2px !important; line-height: 18.2px !important; margin-top: -18px; display: none;"></div>
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 13px !important; line-height: 15px !important; z-index: 0; opacity: 0;">#include&lt;fstream&gt;  

void main()
{
ifstream fin(“C:\1.exe”, ios::nocreate|ios::binary);
if (!fin) {
cout << “File open error!\n”;
return;
}
ofstream fout(“C:\2.exe”, ios::binary);
char c[1024];
while (!fin.eof())
{
fin.read(c, 1024);
fout.write(c, fin.gcount());
}
fin.close();
fout.close();
cout << “Copy over!\n”;
}








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

#include<fstream>  
  
void main ( )   
{   
ifstream fin ( “C:\1.exe” , ios :: nocreate | ios :: binary ) ;   
if ( ! fin ) {   
cout << “File open error!\n” ;   
return ;   
}   
ofstream fout ( “C:\2.exe” , ios :: binary ) ;   
char c [ 1024 ] ;   
while ( ! fin . eof ( ) )   
{   
fin . read ( c , 1024 ) ;   
fout . write ( c , fin . gcount ( ) ) ;   
}   
fin . close ( ) ;   
fout . close ( ) ;   
cout << “Copy over!\n” ;   
}




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

    <div id="crayon-5b6047e19c705633620787" class="crayon-syntax crayon-theme-github crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style="margin-top: 12px; margin-bottom: 12px; font-size: 13px !important; line-height: 15px !important; height: auto;">

        <div class="crayon-toolbar" data-settings=" show" style="font-size: 13px !important;height: 19.5px !important; line-height: 19.5px !important;"><span class="crayon-title"></span>
        <div class="crayon-tools" style="font-size: 13px !important;height: 19.5px !important; line-height: 19.5px !important;"><div class="crayon-button crayon-nums-button crayon-pressed" title="切换是否显示行编号"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-plain-button" title="纯文本显示代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-wrap-button" title="切换自动换行"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-expand-button" title="点击展开代码" style="display: none;"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-copy-button" title="复制代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-popup-button" title="在新窗口中显示代码"><div class="crayon-button-icon"></div></div></div></div>
        <div class="crayon-info" style="min-height: 18.2px !important; line-height: 18.2px !important;"></div>
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 13px !important; line-height: 15px !important; z-index: 0; opacity: 0;">#include&lt;iostream&gt;  

include<fstream>

include<string>

using namespace std;
ifstream& open_file(ifstream &in,const string &file)
{
in.close();
in.clear();
in.open(file.c_str());
return in;
}
int main()
{
ifstream file;
open_file(file,”1.txt”);
string s;
while(getline(file,s))
{
cout<<s<<endl;
}
file.close();
return 0;
}








1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

#include<iostream>  
#include<fstream>  
#include<string>  
using namespace std ;   
ifstream & open_file ( ifstream & in , const string & file )   
{   
     in . close ( ) ;   
     in . clear ( ) ;   
     in . open ( file . c_str ( ) ) ;   
     return in ;   
}   
int main ( )   
{   
     ifstream file ;   
     open_file ( file , “1.txt” ) ;   
     string s ;   
     while ( getline ( file , s ) )   
     {   
         cout << s << endl ;   
     }   
     file . close ( ) ;   
     return 0 ;   
}





在C++中输入输出到指定文件,或者从指定文件中读出数据使用fstream类较为方便。

1.将数据写到磁盘的指定文件中

首先第一步是加头文件#include <fstream>,引入库函数

第二步,声明一个ofstream对象,调用ofstream的成员函数open函数,与指定的文件相关联

第三步,使用<<向文件中写入数据,注意<<操作符已经在库函数里重载过,所以直接调用即可。

最后一步,关闭输出流,调用close()函数


  
  
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. int main(){
  5. ofstream outfile;
  6. outfile.open( “D:\\data.txt”);
  7. outfile<< “随机产生的序列:”<< endl;
  8. for( int i= 0;i< 10;i++){
  9. outfile<<i<< endl;
  10. }
  11. outfile.close();
  12. return 0;
  13. }

在D盘data.txt文件中,应该是这样的效果:


注意,这里的data.txt文件可以提前创建,当然也可以有程序自动创建,也就是说当程序执行到该步时,发现该目录下没有该文件,那么会自动地生成一个文本文件。

在这里有时候会出现这样的问题,当我的代码是这样的:


  
  
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. int main(){
  5. ofstream outfile;
  6. outfile.open( "D:\\data.txt");
  7. outfile<< "随机产生的序列:"<< endl;
  8. for( int i= 0;i< 10;i++){
  9. outfile<<i<< " "; //注意这行与上面的区别
  10. }
  11. outfile.close();
  12. return 0;
  13. }

本意是想将数字横着输出一行,那么到底有没有实现这样的功能呢?

这里要分情况,如果是Dev或者其他比较流行的编译器,是没有任何问题的,效果如下:


但如果是Microsoft visual 6.0这种比较老式的编译器,就会出现这样的情况:


很明显,数字不见了。在此声明,这种情况只会在比较老式的编译器中出现。

原因是要写入的数据在缓冲区内,还没有保存到文本中,解决办法是写完之后刷新一次,调用flush()函数来清空缓冲区。


  
  
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. int main(){
  5. ofstream outfile;
  6. outfile.open( "D:\\data.txt");
  7. outfile<< "随机产生的序列:"<< endl;
  8. for( int i= 0;i< 10;i++){
  9. outfile<<i<< " "; //注意这行与上面的区别
  10. }
  11. outfile.flush();
  12. outfile.close();
  13. return 0;
  14. }
这里需要说明一下原理:

当程序向输出设备中输出数据时,输出的数据先被存放在计算机缓冲区(Buffer)内。当缓冲区存满时,这些数据才真正地输出到输出设备。但是,如果输出的字符序列中出现了endl控制符,那么缓冲区内的所有数据将立即输出到输出设备,而无论缓冲区是否已经存满。因此,endl的作用将光标移动到输出设备中下一行开头处,并且清空缓冲区。
很有可能,出现在程序终止时,并没有输出所有的输出数据的情况。这是因为在程序终止时,缓冲区不一定是满的,所有也就没有将缓冲区的数据写到输出设备。
在C++中,可以使用flush函数来清空缓冲区,即使缓冲区中的数据不是满的。


2.将磁盘文件中的数据读到控制台

原理和写到文件类似,就是一个逆过程。


  
  
  1. #include <iostream>
  2. #include <fstream>
  3. using namespace std;
  4. int main(){
  5. ifstream infile;
  6. infile.open( "D:\\data.txt");
  7. string str;
  8. infile >> str;
  9. cout<<str<< endl;
  10. infile.close();
  11. return 0;
  12. }



            </div>

以下文章转载于:https://blog.csdn.net/seadplus/article/details/7802346









1
2
3

fstream   // 文件流  
ifstream  // 输入文件流  
ofstream  // 输出文件流





    <div id="crayon-5b6047e19c6d1302840318" class="crayon-syntax crayon-theme-github crayon-font-monaco crayon-os-pc print-yes notranslate" data-settings=" minimize scroll-always" style="margin-top: 12px; margin-bottom: 12px; font-size: 13px !important; line-height: 15px !important; height: auto;">

        <div class="crayon-toolbar" data-settings=" show" style="font-size: 13px !important;height: 19.5px !important; line-height: 19.5px !important;"><span class="crayon-title"></span>
        <div class="crayon-tools" style="font-size: 13px !important;height: 19.5px !important; line-height: 19.5px !important;"><div class="crayon-button crayon-nums-button crayon-pressed" title="切换是否显示行编号"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-plain-button" title="纯文本显示代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-wrap-button" title="切换自动换行"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-expand-button" title="点击展开代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-copy-button" title="复制代码"><div class="crayon-button-icon"></div></div><div class="crayon-button crayon-popup-button" title="在新窗口中显示代码"><div class="crayon-button-icon"></div></div></div></div>
        <div class="crayon-info" style="min-height: 18.2px !important; line-height: 18.2px !important; margin-top: -18px; display: none;"></div>
        <div class="crayon-plain-wrap"><textarea wrap="soft" class="crayon-plain print-no" data-settings="dblclick" readonly="" style="tab-size: 4; font-size: 13px !important; line-height: 15px !important; z-index: 0; opacity: 0;">#include &lt;fstream&gt;  

//创建一个文本文件并写入信息
//同向屏幕上输出信息一样将信息输出至文件









1
2
3

fstream   // 文件流  
ifstream  // 输入文件流  
ofstream  // 输出文件流


猜你喜欢

转载自blog.csdn.net/du_shuang/article/details/81319977
今日推荐