读写文件的基本操作

  •  读写文本文件的Demo

#include <iostream>
#include <fstream> 
#include <string>

//1 文本文件  写文件
void Write_File_Data()
{
    ofstream ofs; //创建流对象
    ofs.open("test.txt", ios::out);//打开文件----以写的方式
    ofs << "名字 :张三" << endl;  //写入内容
    ofs << "年龄 : 18"<< endl;
    ofs.close();  //关闭文件
}
//2 文本文件  读文件   
void Read_File_Data()
{
    ifstream ifs; //创建流对象
    ifs.open("test.txt", ios::in);//打开文件----以读的方式
    if( !ifs.is_open())
/*上面三行也可等价写为下面这种形式
    ifstream ifs("test.txt"); //创建流对象
    if( !ifs)*/
    {
        cout <<"open fail"<<endl;
        return;
    }
    char buf[1024] = {0};
//读数据法1-3任选一种可用
    //读数据   法1
    // while(ifs >> buf) //读完所有数据将会退出while
    // {
    //     cout << buf << endl;
    // }
    //读数据   法2
    /*while (ifs.getline(buf,sizeof(buf))) //读取最多sizeof(buf)个数据
    {
         cout << buf << endl;
    }*/
    //读数据   法3
    string buffer;
    while(getline(ifs,buffer))
    {
        cout << buffer <<endl;
    }
    ifs.close();  //关闭文件    
}

int main()
{
    Write_File_Data();
    Read_File_Data();
    return 0;
}
  •  读写二进制文件的Demo

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

//3 二进制文件  写文件
//打开的文件可能会乱码
void Write_Binary_Data()
{
    ofstream ofs;
    ofs.open("person.txt",ios::binary);  //打开文件---以二进制方式
    char name[10] = {'t','e','x','t'};
    ofs.write((const char* )name,4);
    ofs.close();
}

//4 二进制文件  读文件
void Read_Binary_Data()
{
    ifstream ifs;
    ifs.open("person.txt",ios::in | ios::binary);  //打开文件---以二进制方式
    if( !ifs.is_open())
    {
        cout <<"open fail"<<endl;
        return;
    }
    char name[10];
    ifs.read(name, 4);

    cout << name << endl;
    ifs.close();
}



int main()
{
    Write_Binary_Data();
    Read_Binary_Data();
    return 0;
}
  •  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值