复制文本类文件:
#include"iostream"
#include"string"
#include"fstream"
#include"stdlib.h"
using namespace std;
int main()
{
fstream file;
char filename[512];
cout<<"打开文件:";
cin>>filename;
file.open(filename,ifstream::in);
if(!file.is_open())
{
cout<<"文件不在在!"<<endl;
exit(1);
}
else
{
string str;
ofstream anotherfile("d:\\fanyajing.txt");
while(!file.eof())
{
getline(file,str);
anotherfile<<str<<endl;
}
anotherfile.close();
}
return 0;
}
复制任何格式文件:
#include <iostream>
#include <fstream>
using namespace std;
int main ()
{
int length;
char * buffer;
char filename[512];
ifstream infile;
ofstream outfile;
cout<<"打开文件:";
cin>>filename;
infile.open (filename, ifstream::binary );
if(!infile.is_open())
{
cout<<"文件不存在"<<endl;
return 0;
}
// 获取文件长度:
infile.seekg (0, ios::end);
length = infile.tellg();
infile.seekg (0, ios::beg);
// 分配内存空间:
buffer = new char [length];
// 读取块数据:
infile.read (buffer,length);
infile.close();
//复制保存文件:
outfile.open("c:\\out.jpg",ofstream::binary); //不同格式图片改不同扩展名就OK!
outfile.write (buffer,length);
delete[] buffer;
return 0;
}
本文提供两个C++示例程序,演示如何复制文本文件及二进制文件。首先通过字符流实现文本文件的逐行复制;接着使用缓冲区一次性读取整个文件内容的方式复制二进制文件。
619

被折叠的 条评论
为什么被折叠?



