用I/O流建立一个text.txt并写入字符。

来源:互联网 发布:宁波二手房成交数据 编辑:程序博客网 时间:2024/05/23 00:48

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    ofstream ok;
    ok.open("test1.txt",ios::out);
    ok<<"成功";
    ok.close();
    return 0;
}

拷贝zhy.txt文件到新的文件,应该如何写?

#include<iostream>
#include<fstream>
using namespace std;
void copyfile(const char* src,const char* des)
{
//src:源文件名称  des:目标文件名称 bits_to_copy:想复制的字节数
    fstream infile;
    fstream outfile;
    char buf;
     
    infile.open(src,ios::in|ios::binary);
    if(!infile){cout<<"error";exit(-1);}
    outfile.open(des,ios::trunc|ios::binary|ios::out);
    if(!outfile){cout<<"error";exit(-1); }
   
    while(infile.read( &buf,sizeof(buf)) )
    {                              
        outfile.write( &buf,sizeof(buf));
    }
    outfile.close();
    infile.close();
}
int main()
{
   copyfile("zhy.txt","new.txt");
   return 0;
}
另一个版本的函数:

void copyfile(const char* src,const char* des)
{
    fstream infile(src,ios::binary);
    fstream outfile(des,ios::binary); ;
          
    outfile<< infile.rd_buf();
}
 

原创粉丝点击