使用std–fstream处理文件「建议收藏」

使用std–fstream处理文件「建议收藏」fstream文件操作总结文件的操作一直在用,在此总结一下:fstream的使用std::fstream从std::ofstream继承写入文件的功能,从std::ifstream继承读取文件的功能.包含头文件#include使用open()和close()打开和关闭文件#include#includeusingnamespa

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

fstream文件操作总结

文件的操作一直在用,在此总结一下:fstream的使用

std::fstream从std::ofstream继承写入文件的功能,从std::ifstream继承读取文件的功能.

包含头文件

 #include <fstream>

  1. 使用open( )和close( )打开和关闭文件
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    fstream myFile;
    //如果不存在即创建新文件
    myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::out|ios_base::trunc);

    if (myFile.is_open())
        cout << "open is ok " << endl;
    myFile.close();
    system("pause");
}

输出结果:
这里写图片描述

open( )函数:第一个参数是要打开的文件的路径和名称(或指定当前路径),第二参数是文件的打开模式。
具体属性可参考网址
这里写图片描述

其他文件读取方式:

//使用构造函数打开
fstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::out | ios_base::trunc);
    // 只想打开文件写入
ofstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::out);
    // 只想打开文件读取
ifstream myFile("F:\\argv_test\\hello_argv\\helloFile0.txt", ios_base::in);

2.使用open( )创建及写入文本,使用运算符<<

#include<iostream>
#include<fstream>
using namespace std;
int main()
{
    fstream myFile;
    //如果不存在即创建新文件
    myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::out|ios_base::trunc);
    if (myFile.is_open())
        cout << "open is ok " << endl;
    // 写入文本
    myFile << "hello fstream" << endl;
    cout << "Finished" << endl;
    myFile.close();
    system("pause");
}

3.使用open( )创建及读入文本,使用运算符>>

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    fstream myFile;
    //如果不存在即创建新文件
    myFile.open("F:\\wzz_job\\face_confirm\\argv_test\\hello_argv\\helloFile.txt",ios_base::in);
    if (myFile.is_open())
        cout << "open is ok " << endl;

    string fileTxt;
    while (myFile.good())
    {
        getline(myFile,fileTxt);
        cout << fileTxt << endl;

    }
    cout << "Finished" << endl;
    myFile.close();
    system("pause");
}

txt文件内容
这里写图片描述
输出
这里写图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/192840.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号