zoukankan      html  css  js  c++  java
  • C++学习笔记四之文件操作

    一、文本文件---写文件

    1)写文件步骤

    2) 文件打开方式

    3)代码实例

    二、文本文件---读文件

    三、二进制文件---写文件

    四、二进制文件---读文件

    C++中对文件操作需要包含头文件<fstream>;

    文件类型分为两种:文本文件和二进制文件;

    操作文件的三大类:1.ofstream(写操作);2.ifstream(读操作);3.fstream(读写操作)。

    一、文本文件---写文件

    1)写文件步骤:

    ①包含头文件#include<fstream>

    ②创建流对象 ofstream ofs;

    ③打开文件ofs.open("path", 打开方式);

    ④写数据ofs<<"写入的数据";

    ⑤关闭文件ofs.close();

    2)文件打开方式

    注:文件打开方式可以配合使用,利用 | 操作符。例如:用二进制文件写文件ios::binary | ios::out。

    3)代码实例

    #include<iostream>
    #include<string>
    #include"A.h"
    #include<fstream>//1.包含头文件
    using namespace std;
    
    int main()
    {
        //②创建流对象 ofstream ofs;
        ofstream ofs;
    
        //③打开文件ofs.open("path", 打开方式);
        ofs.open("test.txt", ios::out);
    
        //④写数据ofs << "写入的数据";
        ofs << "hello world!";
    
        //⑤关闭文件ofs.close();
        ofs.close();
    
        system("pause");
        return 0;
    }

    二、文本文件---读文件

    1)读文件步骤

    ①包含头文件#include<fstream>

    ②创建流对象 ifstream ifs;

    ③打开文件并判断文件是否打开成功 ifs.open("path", 打开方式);

    ④读文件(四种方式读取)

    ⑤关闭文件ifs.close();

    2)代码实例

    #include<iostream>
    #include<string>
    #include"A.h"
    #include<fstream>//1.包含头文件
    using namespace std;
    
    int main()
    {
        //②创建流对象 ofstream ofs;
        ifstream ifs;
    
        //③打开文件并判断文件是否打开成功 ifs.open("path", 打开方式);
        ifs.open("test.txt", ios::in);
        if (!ifs.is_open())
        {
            cout << "文件打开失败!" << endl;
            system("pause");
            return 0;
        }
    
        //④读数据
        //法一
        /*char buf[1024] = { 0 };
        while (ifs >> buf)
        {
            cout << buf << endl;
        }*/
    
        //法二
        /*char buf[1024] = { 0 };
        while (ifs.getline(buf,sizeof(buf)))
        {
            cout << buf << endl;
        }*/
        //法三
        /*string str;
        while (getline(ifs, str))
        {
            cout << str << endl;
        }*/
        //法四
        char c;
        while ((c=ifs.get())!=EOF)//EOF:end of file
        {
            cout << c << endl;
        }
    
        //⑤关闭文件ofs.close();
        ifs.close();
    
        system("pause");
        return 0;
    }

    三、二进制文件---写文件

    ①打开方式指定为  ios::binary | ios::out ;

    ②调用write函数写文件:ostream &write(const char* buf, int len);

    四、二进制文件---读文件

    ①读文件调用函数read:istream &read(char* buf, int len);

  • 相关阅读:
    hdu4734 F(x)
    hdu2089 不要62 两解
    luogu2602 [ZJOI2010]数字计数 两解
    lemon
    UVA1218 完美的服务 Perfect Service
    luogu HNOI2003消防局的设立
    uva10891 game of sum
    uva10635 Prince and Princess
    UVA1394 And Then There Was One
    uva10003切木棍
  • 原文地址:https://www.cnblogs.com/mango1997/p/14548799.html
Copyright © 2011-2022 走看看