C++初学者指南-2.输入和输出---文件输入和输出

C++初学者指南-2.输入和输出—文件输入和输出

1.写文本文件

使用: std::ofstream(输出文件流)

#include <fstream>  // 文件流头文件
int main () {
  std::ofstream os{"squares.txt"};  // 打开文件

  // 如果文件流没问题表示可以写入文件
  if (os.good()) {
    for (int x = 1; x <= 6; ++x) { 
      // 写入:x值空格x二次方的值和换行符
      os << x << ' ' << (x*x) << '\n';
    }
  }
}  // 文件会自动关闭

上面代码:

  • 创建一个名为squares.txt的新文件
  • 如果文件已存在则覆盖!
  • 每行写 2 个数字,用空格分隔。
squares.txt
1·1\n
2·4\n
3·9\n
4·16\n
5·25\n
6·36\n

2.读文本文件

使用: std::ifstream(输入文件流)

#include <iostream>
#include <fstream>  // 文件流头文件
int main () {
  std::ifstream is{"squares.txt"};  // 打开文件
  // 如果文件流没问题则可以读取
  if ( is.good() ) {
    double x, y;
    // 只要有任何两个可读的数值,就读取出来
    while( is >> x >> y ) {
      // 打印 x,y这对值
      cout << x << "² = " << y << "\n"; 
    }
  }
}  // 文件自动关闭
squares.txt
1·1\n
2·4\n
3·9\n
4·16\n
5·25\n
6·36\n

输出:

1² = 1
2² = 4
3² = 9
4² = 16
5² = 25
6² = 36

3.打开关闭文件

在创建流对象和析构流对象时

int main (int const argc, char const*const* argv) {
  if (argc > 1) {
    // 使用C风格字符串作为文件名
    std::ofstream os { argv[1] };} // 自动关闭
  else {
    // 使用std::string(C++11)
    std::string fn = "test.txt";
    std::ofstream os { fn };} // 自动关闭
}

使用open和close

void bar () {
  std::ofstream os;                 
  os.open("squares.txt");     
  …
  os.close();  
  // open another file:
  os.open("test.txt");  
  …
  os.close();  
}

4.文件打开的模式

默认

ifstream is {"in.txt", ios::in};
ofstream os {"out.txt", ios::out};   (覆盖现有文件)

追加到现有文件

ofstream os {"log.txt", ios::app};

二进制方式

ifstream is {"in.jpg", ios::binary};
ofstream os {"out.jpg", ios::binary};
// 我们以后会学到这一切是什么意思的...
std::uint64_t i = 0;
// 读取二进制数据
is.read(reinterpret_cast<char*>(&i), sizeof(i));
// 写入二进制数据
os.write(reinterpret_cast<char const*>(&i), sizeof(i));

运行示例程序

#include <iostream>
#include <fstream>
#include <cstdint>

int main (int argc, char* argv[]) {
    if (argc < 3) {
        std::cerr << "usage: " << argv[0] << " <integer> <filename>\n";
        return 0;
    }
    std::string filename {argv[2]};
    {   // write binary
        std::uint64_t i = atoi(argv[1]);
        std::cout << "writing: " << i << " to " << filename << "\n";
        std::ofstream os {filename, std::ios::binary};
        if (os.good()) {
            os.write(reinterpret_cast<char const*>(&i), sizeof(i));
        }
    }
    {   // read binary
        std::uint64_t i = 0;
        std::ifstream is {filename, std::ios::binary};
        if (is.good()) {
            is.read(reinterpret_cast<char*>(&i), sizeof(i));
            std::cout << "read as: " << i << "\n";
        }
    }
}

运行上面代码

附上原文链接
如果文章对您有用,请随手点个赞,谢谢!^_^
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值