1、将文件复制到另一个文件中
#include <fstream.h>
int main()
{
char ch;
ifstream f1 ("file_from");
if(!f1)
{
cout<<"can not open 'file_from'for input"<<endl;
return 1;
}
ofstream f2("file_to");
if(!f2)
{
cout<<"can not open 'file_to' for output."<<endl;
return 1;
}
while(f2&&f1.get(ch)) f2.put(ch);
f1.close();
f2.close();
return 0;
}
2、任意格式文件的复制
/*
可以实现任意文件格式的复制
*/
#include <iostream>
using namespace std;
#define length 100
int main()
{
//打开读文件
FILE* file=NULL;
// rb 只读方式打开一个二进制文件,文件必须存在
file=fopen("Think Different.flv","rb");
if(NULL==file)
{
cout<<"open read file fault!"<<endl;
exit(1);
}
//打开写文件
FILE* w_file;
//wb 只写打开或新建一个二进制文件;只允许写数据
w_file=fopen("Think DifferentFJ.flv","wb");
if(NULL==file)
{
cout<<"open write file fault!"<<endl;
exit(1);
}
//缓存字符串
char buf[length];
int nRead=0;
bool TRUE=true;
while(TRUE)
{
//nRead为实际中读取的字节数
//fread以1个字节为单位,每次读取length个字节
nRead=fread(&buf,1,length,file);
//nRead<length,说明即将读取结束
if(nRead<length)
TRUE=false;
//将buf中的数据写入文件
fwrite(&buf,1,nRead,w_file);
}
//关闭写文件
fclose(w_file);
//关闭读文件
fclose(file);
return 0;
}
3、把一个整数,一个浮点数和一个串写到test文件中
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ofstream outfile ("test.txt");
if(!outfile)
{
cout<<"can not open file"<<endl;
return 1;
}
outfile<<19<<"/t"<<123.23<<"/t";
outfile<<"this is a short text file"<<endl;
outfile.close();
return 0;
}