C++——文件流

文件流有点类似标准输出和标准输入;文件类型可以分为两种:文件流包括文本文件和二进制文件,生活中大量的信息都是用文本文件来保存的,二进制文件保存的只是二进制数据,利用二进制模式,你可以操作图像等文件。

ifstream – 从已有的文件读
ofstream – 向文件写内容
fstream - 打开文件供读写

一,写文件ofstream

#include <fstream>
#include<iostream>
#include<string>
using namespace std;

void main()
{
    //打开文件,使其对应输出流out
    ofstream out("F:\\vs2010\\hello world\\Test.txt");
    if(!out)
    {
        cout<<"不可以打开文件"<<endl;
        exit(0);
    }

    //写入文件
    out<<"hello world"<<endl;//直接将字符串写入文件
    cout<<"hello world"<<endl;
    char ch;
    cout<<"请输入将要写入文件的字符,直到回车结束:";
    while( cin.get(ch) )//从键盘中输入数据到文件
    {
        if(ch=='\n') break;
        out.put(ch);
        cout.put(ch);
    }  

    //关闭文件
    out.close();
}

这里写图片描述

二,读文件ifstream

#include <fstream>
#include<iostream>
#include<string>
using namespace std;

void main()
{
    //打开文件,使其对应输出流in
    ifstream in("F:\\vs2010\\hello world\\Test.txt");
    if(!in)
    {
        cout<<"不可以打开文件"<<endl;
        exit(0);
    }

    //读文件
    string str;
    getline(in,str);
    cout<<str<<endl;
    char ch;
    while(in.get(ch))
    {
        cout.put(ch);
    }

    //关闭文件
    in.close();
}

这里写图片描述

三,文件流fstream

#include <fstream>
#include<iostream>
#include<string>
using namespace std;

void main()
{
    fstream file("F:\\vs2010\\hello world\\FILE.txt",ios::out);//创建文件流file,打开方式为out,所以此时为输出文件流
    if (!file)
    {
        cout<<"不能打开文件"<<endl;
        exit(0);
    }
    file<<"hello world"<<12<<" "<<'12'<<'c'<<endl;
    file.close();

    file.open("F:\\vs2010\\hello world\\FILE.txt",ios::in);//打开方式为in,所以为输入文件流
    string str;
    getline(file,str);
    cout<<str<<endl;
    file.close();
}

这里写图片描述

四,其他

#include <fstream>
#include<iostream>
#include<string>
using namespace std;

void main()
{
    ifstream in("F:\\vs2010\\hello world\\Test.txt");//打开文件Test.txt,将其对应为输入文件流in
    ofstream out("F:\\vs2010\\hello world\\Out.txt");//打开文件Out.txt,将其对应为输出文件流out
//对文件的操作将变为对文件流in和out的操作


    for(string str;getline(in,str); )//getline(in,str):从in中读入一行数据放入str中,整行整行读入
    {
        out<<str<<endl;//将str和endl输出到out中,即输出到文件Out.txt中
        cout<<str<<endl;//将str和endl输出到黑框中
    }
}

实现了文件的复制,将创建一个新的文件Out.txt,该文件复制了Text.txt中的内容,且
这里写图片描述

打开文件还可以用以下方法:

#include <fstream>
#include<iostream>
#include<string>
using namespace std;

void main()
{
    ofstream out;
    out.open("F:\\vs2010\\hello world\\File.txt");

    out<<"hello world"<<endl<<75<<" "<<"75"<<endl;
    cout<<"hello world"<<endl<<75<<" "<<"75"<<endl;

    out.close();
}

这里写图片描述

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值