C++ 文件操作之文件流操作

简介

本文主要整理了一些博主的优质内容,进行一些优质整合。(后续进行更多补充)

常见的流操作如下:

#include <fstream>
ofstream         //文件写操作 内存写入存储设备 
ifstream         //文件读操作,存储设备读区到内存中
fstream          //读写操作,对打开的文件可进行读写操作 

具体一些代码功能实现

ifstream配合getline读取文件每行数据

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    string str;
    ifstream ifs('test.txt');
    if(!ifs)
    {
        cout<<'open file fail!'<<endl;
        return 1;
    }
    while( getline(ifs,str))
    {
        cout<<str<<endl;
    }
    return 0;
}
// 输出12345678910111213141516171819

ofstream实现对文件写入每行数据

     // writing on a text file
    #include <fiostream.h>
    int main () {
        ofstream out("test.txt");
        if (out.is_open()) 
       {
            out << "This is a line.\n";
            out << "This is new line.\n";
            out.close();
        }
        return 0;
    }
   //结果: 在out.txt中写入:
   //This is a line.
   //This is new line.

fstream对文件读写操作

#include<fstream.h>
void main()
{
  fstream f("d:\\try.txt",ios::out);
  f<<1234<<' '<<3.14<<'A'<<"How are you"; //写入数据
  f.close();
  f.open("d:\\try.txt",ios::in);
  int i;
  double d;
  char c;
  char s[20];
  f>>i>>d>>c;               //读取数据
  f.getline(s,20);
  cout<<i<<endl;             //显示各数据
  cout<<d<<endl;
  cout<<c<<endl;
  cout<<s<<endl;
  f.close();
}
//输入结果:
//1234
//3.14
//A
//How are you

ifstream和ofstream操作二进制文件

#include<fstream.h>
void main()
{
  ifstream fin("C:\\1.exe",ios::nocreate|ios::binary);
  if(!fin){
    cout<<"File open error!\n";
    return;
  }
  ofstream fout("C:\\2.exe",ios::binary);
  char c[1024];
  while(!fin.eof())
  {
    fin.read(c,1024);
    fout.write(c,fin.gcount());
  }
  fin.close();
  fout.close();
  cout<<"Copy over!\n";
}

ifstream一次读一个字符

#include<fstream.h>
void main()
{
  ifstream fin("d:\\简介.txt",ios::nocreate);
  if(!fin){
    cout<<"File open error!\n";
    return;
  }
  char c;
  while((c=fin.get())!=EOF)cout<<c;    //注意结束条件的判断
  fin.close();
}

ifstream读到特殊字符停止读取

include<fstream.h>
void main()
{
  ifstream fin("d:\\简介.txt",ios::nocreate);
  if(!fin){
    cout<<"File open error!\n";
    return;
  }
  char c[80];
  while(fin.get(c,80,'\0')!=NULL)cout<<c; //注意结束条件的判断
  fin.close();
}

上面主要摘自:
博主wode0239

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

路过的小熊~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值