C++实现文件操作(源码)!

都是很简单的代码,那就闲话少说,切入正题!

文件写入:

 

<!----> #include  < fstream >
#include 
< iostream >  
using   namespace  std;
int  main(){
string  str;
ofstream 
out ( " d.txt " );
str
= " 床前明月光\n疑是地上霜\n举头望明月\n低头思故乡\n " ;
out << str << endl;
return   0 ;   
}

文件读取:

 

<!----> #include  < fstream >
#include 
< iostream >  
using   namespace  std;
int  main(){
ifstream 
in ( " a.txt " );
for ( string  str;getline( in ,str);)
cout
<< str << " \n " ;
return   0 ;    
}

 

文件复制

 

<!----> #include  < fstream >
#include 
< iostream >  
using   namespace  std;
int  main(){
ifstream 
in ( " a.txt " );
ofstream 
out ( " b.txt " );
for ( string  str;getline( in ,str);)
out << str << endl;
cout
<< " 文件复制成功!!! " ;
return   0 ;    
}

 

筛法判断素数程序

<!----> #include  < iostream >
#include 
< vector >
#include 
< fstream >
using   namespace  std;
int  main(){
vector
< int >  prime( 10000 , 1 );
for ( int  i = 2 ;i < 100 ; ++ i)
        
if (prime[i])
        
for ( int  j = i;i * j < 10000 ; ++ j)
        prime[i
* j] = 0 ;
ifstream 
in ( " c.txt " );
for ( int  a; in >> &&  a > 1   &&  a < 10000 ;)
cout
<< a << "  is  " << (prime[a] ? "" : " not  " ) << "  a prime.\n " ;    
}

 

c.txt文件中写入一系列小于10000的整数,并换行,就可以实现素数判断,因为也涉及文件的读取操作,所以一并给出。

 

感觉C++文件流操作好esay啊!Java读取文件还要复杂一点。

 

 

你可能感兴趣的:(C++,c,C#,J#)