zoukankan      html  css  js  c++  java
  • C++ fstream文件操作

    代码如下:

    #include "stdafx.h"
    
    #include<string>
    
    #include<iostream>  //是因为要使用cout
    #include<fstream>    //必须要加,因为要使用ifstream
    int main()
    
    {
    
        //把字符串写进文件中
        std::string  str_data = "xxxxxxxxxxxx";
        std::ofstream ofs("D:\out.txt");
        ofs << str_data;
    
        ofs.close();
    
    
        //从文件中读取内容
    
        std::ifstream fin("D:\out.txt");
        if (!fin)
        {
            std::cout << "文件不能打开" << std::endl;
        }
        else
        {
            char buffer[80];
            fin >> buffer;   
            fin.close();
            std::cout << buffer << std::endl;
        }
    
    }

    打开文件的方式在类iOS(是所有流式I/O类的基类)中定义.

    常用的值如下:
      ios::app:   以追加的方式打开文件
      ios::ate:   文件打开后定位到文件尾,ios:app就包含有此属性
      ios::binary:   以二进制方式打开文件,缺省的方式是文本方式。两种方式的区别见前文
      ios::in:     文件以输入方式打开(文件数据输入到内存)
      ios::out:   文件以输出方式打开(内存数据输出到文件)
      ios::nocreate: 不建立文件,所以文件不存在时打开失败
      ios::noreplace:不覆盖文件,所以打开文件时如果文件存在失败
      ios::trunc:  如果文件存在,把文件长度设为0

    例如要以二进制方式,则可以这样写:
        std::ofstream ofs("D:\out.txt",std::ios::binary);

    补充:fstream是对文件操作输入输出,而iostream是对屏幕操作输入输出,两个不同概念

  • 相关阅读:
    Python运算符
    Python中的变量
    Chapter 4. Working with Key/Value Pairs
    Chapter 3. Programming with RDDs
    python常见的特异点
    18.天知道练习
    17.vue+axios搭配使用
    16.axios基本使用
    15.记事本练习
    14.v-model指令
  • 原文地址:https://www.cnblogs.com/kevinWu7/p/10163532.html
Copyright © 2011-2022 走看看