C++读写文本文件 08 20 2024

4.1 写文件

步骤如下:

  1. 包含头文件

    #include<fstream>

  2. 创建流对象:

    ofstream os1;

  3. 打开文件:

    of1.open("path",打开方式);

  4. 输出数据:

    of1<<"data";

  5. 关闭文件:

    of1.close();

打开方式 解释
ios::in 读文件方式打开文件
ios::out 写文件方式打开文件
ios::ate 初始位置为文件尾
ios::app 追加方式写文件(常用)
ios::trunc 如果文件存在,先删除,再创建
ios::binary 二进制方式

**注意:**文件打开方式可以用位或操作符配合使用,如: ios:in | ios:binary

复制代码
#include <fstream>
#include <iostream>
using namespace std;
 
int main ()
{
    
   char data[100];
 
   // 以写模式打开文件
   ofstream outfile;
   outfile.open("afile.dat");
 
   cout << "Writing to the file" << endl;
   cout << "Enter your name: "; 
   cin.getline(data, 100);
 
   // 向文件写入用户输入的数据
   outfile << data << endl;
 
   cout << "Enter your age: "; 
   cin >> data;
   cin.ignore();
   
   // 再次向文件写入用户输入的数据
   outfile << data << endl;
 
   // 关闭打开的文件
   outfile.close();
 
   // 以读模式打开文件
   ifstream infile; 
   infile.open("afile.dat"); 
 
   cout << "Reading from the file" << endl; 
   infile >> data; 
 
   // 在屏幕上写入数据
   cout << data << endl;
   
   // 再次从文件读取数据,并显示它
   infile >> data; 
   cout << data << endl; 
 
   // 关闭打开的文件
   infile.close();
 
   return 0;
}

4.2 读文件

步骤如下:

  1. 包含头文件

    #include<fstream>

  2. 创建流对象:

    ifstream ifs1;

  3. 打开文件并判断是否打开成功:

    ifs1.open("path",打开方式);

  4. 读数据:

    四种方式读取;

  5. 关闭文件:

    ifs1.close();

复制代码
#include<iostream>
#include<fstream>
void test01()
{
    ifstream ifs;
    ifs.open("test.txt",ios::in);
    //如果打开失败
    if(!ifs.isopen())
    {
        cout<<"文件打开失败"<<endl;
        return;
    }
    //读数据
    //第一种方式:将所有的空格当做终止条件,没有办法输出空格信息了,空格都被endl回车代替了
    char buff[1024] = { 0 };
    while (ifs >> buff)
    {
        cout << buff<<endl;
    }
    //第二种方式:利用<string>中getline函数 包含头文件<string>
    string buff;
    while(getline(ifs,buff))
    {
        cout<<buff<<endl;
    }
    //第三种方式:利用ifs对象的getline方法来实现
    char buff[1024]={0};
    while(ifs.getline(buff,sizeof(buff)))
    {
        cout<<buff<<endl;
    }
    //第四种方式:字符逐个读取,不用考虑回车换行的问题,因为文件中的\n被读取出来之后输出到控制台上自动就换行了,利用fin.get()函数,这个函数的返回值是它读取到的字符,当遇到EOF的时候返回EOF,通过判断跳出while循环
    char buff = 'a';//随便给字符buff赋初始值
    while((buff=ifs.get()) != EOF)
    {
        cout<<buff;
    }
    //关闭文件
    ifs.close();
}

总结:第一种方法无法读取空格,第二种方法和第三种方法按行读取,一个是string库中的函数,一个是istream中的函数,第四种是把每个字符读出来逐个输出,效率较低而且可能会碰到意想不到的问题.

相关推荐
Forget the Dream32 分钟前
设计模式之责任链模式
java·c++·设计模式·责任链模式
停止重构33 分钟前
【开源】低代码 C++程序框架,Linux多线程程序
c++·低代码·多线程·开源框架·云计算引擎
Joey_friends35 分钟前
【Linux】线程详解
开发语言
Duramentee36 分钟前
C++ 设计模式 十二:责任链模式 (读书 现代c++设计模式)
c++·设计模式·责任链模式
_GR41 分钟前
Qt开发⑧Qt的窗口_下_浮动窗口+对话框
开发语言·css·c++·qt·microsoft
Good Note1 小时前
Golang——常用库context和runtime
开发语言·爬虫·golang
萌の鱼1 小时前
leetcode 3183. 达到总和的方法数量
数据结构·c++·算法·leetcode
清河__1 小时前
【Go】十七、grpc 服务的具体功能编写
开发语言·后端·golang
Forget the Dream1 小时前
设计模式之代理模式
java·c++·设计模式·代理模式
张声录11 小时前
国密算法Sm2工具类--golang实现版
开发语言·后端·golang