美文网首页
C++ 读写文件

C++ 读写文件

作者: 小潤澤 | 来源:发表于2020-03-16 19:54 被阅读0次

文件操作

文本文件 写文件

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

void test01()
{
     //1.包括头文件fstream
     //2.创建流对象
     ofstream ofs;
     //3.指定打开方式
     ofs.open("/.../test.txt",ios::out);
     //4.写内容
     ofs<<"姓名:张三"<<end1;
     ofs<<"性别:男"<<end1;
     ofs<<"年龄:18"<<end1;  
    //5.关闭文件
     ofs.close();
}

int main(){
  test01();
  
  system("pause");
  return 0;
}

读文件

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

void test01()
{
     //1.包括头文件fstream
     //2.创建流对象
     ifstream ifs;
     //3.打开方式,并判断是否打开成功
     ifs.open("/.../test.txt",ios::in);

     if(!ifs.is_open())
   {
       cout<<"文件打开失败"<<end1;
       return;
  }
    
     //4.读内容
    //第一种
     char buf[1024] = {0};
     while (ifs >> buf)
  {
       cout<<buf<<end1;
  }
   //第二种
     char buf[1024] -= { 0 };
     while (ifs.getline(buf, sizeof(buf)))
  {
       cout<<buf<<end1;
  }
     //5.关闭文件
      ifs.close();
}

int main(){
  test01();
  
  system("pause");
  return 0;
}

接下来我们看下用string来进行读文件

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

void test01()
{
     //1.包括头文件fstream
     //2.创建流对象
     ifstream ifs;
     //3.打开方式,并判断是否打开成功
     ifs.open("/.../test.txt",ios::in);

     if(!ifs.is_open())
  {
       cout<<"文件打开失败"<<end1;
       return;
  }
    
     //4.读内容
    //第三种
     string buf;
     while (getline(ifs.buf)
  {
       cout<<buf<<end1;
  }
      //5.关闭文件
      ifs.close();
}
 
int main(){
  test01();
  
  system("pause");
  return 0;
}

第四种是每个字符进行操作

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

void test01()
{
     //1.包括头文件fstream
     //2.创建流对象
     ifstream ifs;
     //3.打开方式,并判断是否打开成功
     ifs.open("/.../test.txt",ios::in);

     if(!ifs.is_open())
   {
        cout<<"文件打开失败"<<end1;
        return;
  }
    
     //4.读内容
    //第四种
     char c;
     while ((c = ifs.get()) ! = EOF)
  {
       cout<<c;
  }
     //5.关闭文件
      ifs.close();

int main(){
  test01();
  
  system("pause");
  return 0;
}

相关文章

  • 2019-03-06 C++二进制文件结构体读取问题

    C与C++的二进制文件读写 参考下面的文章,C/C++读写文本文件、二进制文件 https://blog.csdn...

  • 文件读写总结

    1. C++文件读写详解 1.1. 文件读写操作 使用方式 1.1.1. 打开文件 文件操作通过成员函数open(...

  • c++ 积累

    c++读写文件 写文件 读文件 sudo ln -s /usr/local/cuda-9.1 /usr/local...

  • c++文件读写

    ifstream ifs;连续读写文件时: ifstream 是有状态的对象,一个 ifstream 操作完后一般...

  • C++文件读写

    1、 定义数据流对象指针 对文件进行读写操作首先必须要定义一个数据流对象指针,数据流对象指针有三种类型,它们分别是...

  • c++ 读写文件

    写文件文本 读文件文本 读写二进制文件

  • c++文件读写

    c++的文件读写,其实要导入一个新的头文件,差不多每实现一个新的功能就要导入一个新的头文件,从这个角度来看,还是现...

  • C++ 读写文件

    文件操作 文本文件 写文件 读文件 接下来我们看下用string来进行读文件 第四种是每个字符进行操作

  • C++文件读写

    欲对文件进行读写操作,首先得包含fstream[https://www.jianshu.com/writer]头文...

  • c++ 读写文件

    引用原文址[https://blog.csdn.net/mengsuifengc/article/details/...

网友评论

      本文标题:C++ 读写文件

      本文链接:https://www.haomeiwen.com/subject/dqiqehtx.html