首页 > 其他分享 >IO文件读写与复制

IO文件读写与复制

时间:2023-06-01 18:07:24浏览次数:46  
标签:std cout 读写 ios char 复制 IO using include


文件的复制

#include <iostream>
#include <fstream>
using namespace std;
int CopyFile(char *SourceFile,char *NewFile)
{
ifstream in;
ofstream out;
in.open(SourceFile,ios::binary);//打开源文件
if(in.fail())//打开源文件失败
{
   cout<<"Error 1: Fail to open the source file."<<endl;
   in.close();
   out.close();
   return 0;
}
out.open(NewFile,ios::binary);//创建目标文件 
if(out.fail())//创建文件失败
{
   cout<<"Error 2: Fail to create the new file."<<endl;
   out.close();
   in.close();
   return 0;
}
else//复制文件
{
   out<<in.rdbuf();
   out.close();
   in.close();
   return 1;
}
}
void main()
{
char source[256],NewFile[256];
cout<<"请输入要复制的文件路径:"<<endl;
cin>>source;
cout<<"请输入新文件的路径:"<<endl;
cin>>NewFile;
if(CopyFile(source,NewFile))
{
   cout<<"文件已成功复制..."<<endl;
}
else
{
   cout<<"文件复制失败..."<<endl;
}
cin.get();
cin.get();
}

从hello.txt文件中读取数据并写入到out.txt中

#include "stdafx.h"  
#include <vector>  
#include <string>  
#include <fstream>  
#include <iostream>  
using namespace std;  
int _tmain(int argc, _TCHAR* argv[])  
{  
    ifstream myfile("E:\\hello.txt");  
    ofstream outfile("E:\\out.txt", ofstream::app);  
    string temp;  
    if (!myfile.is_open())  
    {  
        cout << "未成功打开文件" << endl;  
    }  
    while(getline(myfile,temp))  
    {  
        outfile<<temp;  
    }  
    myfile.close();  
    return 0;  
}

利用流复制文件

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;
void cpf(char *a,char *b);

int main()
{
    char sourcefile[100];
    char copyfile[100];
    cout<<"请输入要复制的文件路径"<<endl;
    cin>>sourcefile;
    cout<<"请输入要粘贴的文件路径"<<endl;
    cin>>copyfile;

    cpf(sourcefile,copyfile);

    return 0;
}

void cpf(char *a,char *b)
{
    fstream in(a,ios::in | ios::binary);
    if(!in.is_open())
    {
        cerr<<"源文件不存在"<<endl;
        exit(EXIT_FAILURE);
    }
    fstream out(b,ios::out | ios::binary);
    if(!out.is_open())
    {
        cerr<<"路径错误"<<endl;
        exit(EXIT_FAILURE);
    }
    out<<in.rdbuf();
    cout<<"文件复制成功"<<endl;
}

需要注意的地方

1.文件路径是char数组,传递参数时应该将形参设为指针

2.复制文件应该用ios::binary(二进制模式),原因是使用二进制文件模式时,程序将数据从内存传递给文件,将不会发生任何隐藏的转换,而默认状态下是文本模式,复制的内容可能会发生改变(参见c++ primer plusP695)

3.关于 rebuf():复制文件时是从一个流对象复制流入另外一个流对象,需要使用rebuf(),rebuf()的功能就是使流重定向

4.exit(EXIT_FAILURE)相当于exit(1),exit(EXIT_SUCCESS)相当于exit(0)

5.注意#include 也需要和using namespace std 搭配

利用成员函数复制文件的例子

利用成员函数read()和wirte()复制文件,函数原型如下:

istream &read(char *p,sizeof(p));

ostream &write(char *p,sizeof(p));
#include <iostream>
#include <fstream>
using namespace std;

int main()
{

    fstream in("e:\\1.png",ios::in | ios::binary);
    if(!in.is_open())
    {
        cerr<<"源文件不存在"<<endl;
        exit(EXIT_FAILURE);
    }
    fstream out("e:\\2.png",ios::out | ios::binary);
    if(!out.is_open())
    {
        cerr<<"路径错误"<<endl;
        exit(EXIT_FAILURE);
    }
    in.seekg(0,ios::end);
    long size;
    size = in.tellg();
    char *buf = new char[size];
    in.seekg(ios::beg);
    in.read(buf,size);
    out.write(buf,size);
    delete [] buf;
    cout<<"文件复制成功"<<endl;
    return 0;
}
#include<iostream>
#include<fstream>

void copy(char* src, char* dst);
int main()
{
    using namespace std;
    char src[50] = "E:/test/jdk-8u121-windows-x64.exe";
    char dst[50] = "E:\\test\\jdk-8u121-windows-x64_bak.exe";
    copy(src, dst);

    return 0;
}

void copy(char* src, char* dst)
{
    using namespace std;
    ifstream in(src,ios::binary);
    ofstream out(dst,ios::binary);
    if (!in.is_open()) {
        cout << "error open file " << src << endl;
        exit(EXIT_FAILURE);
    }
    if (!out.is_open()) {
        cout << "error open file " << dst << endl;
        exit(EXIT_FAILURE);
    }
    if (src == dst) {
        cout << "the src file can't be same with dst file" << endl;
        exit(EXIT_FAILURE);
    }
    char buf[2048];
    long long totalBytes = 0;
    while(in)
    {
        //read从in流中读取2048字节,放入buf数组中,同时文件指针向后移动2048字节
        //若不足2048字节遇到文件结尾,则以实际提取字节读取。
        in.read(buf, 2048);    
        //gcount()用来提取读取的字节数,write将buf中的内容写入out流。
        out.write(buf, in.gcount());    
        totalBytes += in.gcount();
    }
    in.close();
    out.close();
}


标签:std,cout,读写,ios,char,复制,IO,using,include
From: https://blog.51cto.com/u_16147764/6397209

相关文章

  • ERROR: Kernel configuration is invalid.
    最简单的linuxhello的驱动源程序//下面是驱动源代码#include<linux/init.h>#include<linux/module.h>staticinthello_init(void){printk(KERN_ALERT"Hello,TekkamanNinja!\n");return0;}staticvoidhello_exit(void){......
  • Docker安装Minio
    //拉取minio镜像dockerpillminio/minio//创建配置文件和文件存储挂载目录mkdir-p/server/minio/configmkdir-p/server/minio/data//启动miniodockerrun-p8095:8095-p8094:8094\--net=host\--nameminio\-d--restart=always\-e"MINIO_ACCESS_KE......
  • MySQL主从复制
    一,概述主从复制是指将主数据库的DDL和DML操作通过二进制日志传到从库服务器中,然后在从库上对这些日志重新执行(也叫重做》,从而使得从库和主库的数据保持同步。MySQL支持一台主库同时向多台从库进行复制,从库同时也可以作为其他从服务器的主库,实现链状复制。MySQL复制的......
  • ‘dependencies.dependency.version‘ for mysql:mysql-connector-java:jar is missin
    项目使用的技术框架是SpringBoot,依赖管理工具是Maven,需要用到数据库所以引入了mysql-connector-java相关jar包。之前项目一直正常的,不会报错,最近更新了一下版本,项目启动的时候直接报错:[INFO]Scanningforprojects...[ERROR][ERROR]Someproblemswereencounteredwhilep......
  • surrounded-regions
    Givena2Dboardcontaining'X'and'O',captureallregionssurroundedby'X'.Aregioniscapturedbyflippingall'O'sinto'X'sinthatsurroundedregion.Forexample,XXXXXOOXXXOXXOXXAft......
  • JAVA 反射应用:Annotation
    SomeClass.javaimportjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;importjava.lang.reflect.Method;publicclassSomeClass{@SomeToken......
  • mysql functions ,LAST_INSERT_ID() 或 自定义主键
    http://dev.mysql.com/doc/refman/5.6/en/information-functions.html LAST_INSERT_ID() 这个值如果各个table都有一个自增的id,那么各个table用各自的LAST_INSERT_ID()  自定义:#固定前缀(2位)+时间戳(13位)+随机数(7位)SELECTCONCAT('AB',#......
  • java.lang.ClassNotFoundException: weblogic.utils.NestedException
    我单元测试的时候报这种错误Causedby:java.lang.ClassNotFoundException:weblogic.utils.NestedException atjava.net.URLClassLoader$1.run(URLClassLoader.java:202) atjava.security.AccessController.doPrivileged(NativeMethod) atjava.net.URLClassLoader.findC......
  • SpringBoot项目中实现读写分离
    背景介绍面对日益增加的系统访问量,数据库的吞吐量面临着巨大瓶颈。对于同一时刻有大量并发读操作和较少写操作类型的应用系统来说,将数据库拆分为主库和从库,主库负责处理事务性的增删改操作,从库负责处理查询操作,能够有效的避免由数据更新导致的行锁,使得整个系统的查询性能得到极......
  • MySql主从复制
    介绍MySQL主从复制是一个异步的复制过程,底层是基于Mysql数据库自带的二进制日志功能。就是一台或多台MySQL数据库(slave,即从库)从另一台MySQL数据库(master,即主库)进行日志的复制,然后再解析日志并应用到自身,最终实现从库的数据和主库的数据保持一致。MySQL主从复制是MySQL数据......