栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

简介

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

常见的流操作如下:

#include 
ofstream         //文件写操作 内存写入存储设备 
ifstream         //文件读操作,存储设备读区到内存中
fstream          //读写操作,对打开的文件可进行读写操作 
具体一些代码功能实现 ifstream配合getline读取文件每行数据
#include
#include
#include
using namespace std;
int main()
{
    string str;
    ifstream ifs('test.txt');
    if(!ifs)
    {
        cout<<'open file fail!'< 
ofstream实现对文件写入每行数据 
     // writing on a text file
    #include 
    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
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< 
ifstream和ofstream操作二进制文件 
#include
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
void main()
{
  ifstream fin("d:\简介.txt",ios::nocreate);
  if(!fin){
    cout<<"File open error!n";
    return;
  }
  char c;
  while((c=fin.get())!=EOF)cout< 
ifstream读到特殊字符停止读取 
include
void main()
{
  ifstream fin("d:\简介.txt",ios::nocreate);
  if(!fin){
    cout<<"File open error!n";
    return;
  }
  char c[80];
  while(fin.get(c,80,'')!=NULL)cout< 

上面主要摘自:
博主wode0239

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/769077.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号