C + + file read / write operations std::ofstream and std::ifstream

Tip: after the article is written, the directory can be generated automatically. Please refer to the help document on the right for how to generate it

preface

This article is mainly to sort out the file operations std::ofstream and std::ifstream in C + +.

1, Introduction to file operation

std::ofstream and std::ifstream belong to fsstream. Fsstream is a class that controls file read and write operations, including std::ofstream and std::ifstream. Note: std::ofstream is used for writing files, and std::ifstream is used for reading files.

2, Use

1. Read file (std::ifstream)

  1. Constructor
//Default constructor 
ifstream();

//Initialize constructor 	   The first parameter filename is the location of the file to be read, and the second parameter mode describes the flag of the i/o mode of the file request, that is, the way to open the file.
explicit ifstream (const char* filename, ios_base::openmode mode = ios_base::in);
explicit ifstream (const string& filename, ios_base::openmode mode = ios_base::in);

How to open a file

member constantaccess
ios_base::inOpen the file as read.
ios_base::outOpen the file as a write.
ios_base::binaryOpen the file in binary mode.
ios_base:: ateWhen opening a file, navigate to the end of the file.
ios_base:: appOpen the file by appending, and all data written to the file is appended at the end of the file.
ios_base::truncWhen a file is opened, the contents before the file are emptied.
  1. Common functions
(1) void open (const   char* filename,  ios_base::openmode mode = ios_base::in);	
(2) void open (const string& filename,  ios_base::openmode mode = ios_base::in);
	Open file function. If the read file operation object is created by the default constructor, you can use the above two functions to open the file.
	
(3) void close()
	Close the file function. After each operation on the file, you need to close the file.
	
(4) bool is_open()
	Judge whether the file reading operation object has opened the file. If it is opened successfully, the return value is true,If the opening fails, the return value is false. 

(5) bool eof()
	It is used to judge whether the end of the file is reached. If it is reached, it returns true,Otherwise return false. 

(6) istream& getline (char* s, streamsize n );
(7) istream& getline (char* s, streamsize n, char delim );
	Used to read the value in the file, if encountered'\n'That is, stop reading if the newline character is. Where parameters s It is used to store the read characters and parameters n Indicates the maximum number of characters that can be read. Parameter delim Indicates that as long as the next character to be read is equal to this, the operation of reading characters will stop.

The operation code for reading files is as follows:

const char FILE_PATH[] = "readTest.txt";//Where readtest Txt file is the file to be read
class MyFileStream
{
public:
    MyFileStream()
    {
    }
    ~MyFileStream()
    {
    }
    void readFileOfIfstream(vector<string>& readStrs)
    {
        ifstream ifs(FILE_PATH,ios_base::in);//read-only

        if(!ifs.is_open())
        {
            cout<<"file open fail"<<endl;
            return;
        }

        while(!ifs.eof())//eof() checks whether the end of the file has been reached
        {
            char readStr[100];
            ifs.getline(readStr,100);
            string str(readStr);
            readStrs.emplace_back(str);
        }
        ifs.close();
    }
};
int main()
{
        MyFileStream  myFileStream;
        vector<string> readStrs;
        myFileStream.readFileOfIfstream(readStrs);
        for(auto data:readStrs)
        {
            cout<<data<<endl;
        }
}

The effect after operation is as follows:

2. File writing (std::ofstream)

  1. Constructor
//Default constructor 
ofstream();

//Initialize constructor 	   The first parameter filename is the location of the file to be read, and the second parameter mode describes the flag of the i/o mode of the file request, that is, the way to open the file.
explicit ofstream (const char* filename, ios_base::openmode mode = ios_base::out);
explicit ofstream (const string& filename, ios_base::openmode mode = ios_base::out);

How to open a file

member constantaccess
ios_base::inOpen the file as read.
ios_base::outOpen the file as a write.
ios_base::binaryOpen the file in binary mode.
ios_base:: ateWhen opening a file, navigate to the end of the file.
ios_base:: appOpen the file by appending, and all data written to the file is appended at the end of the file.
ios_base::truncWhen a file is opened, the contents before the file are emptied.
  1. Common functions
(1) void open (const   char* filename,  ios_base::openmode mode = ios_base::in);	
(2) void open (const string& filename,  ios_base::openmode mode = ios_base::in);
	Open file function. If the write file operation object is created by the default constructor, you can use the above two functions to open the file.
	
(3) void close()
	Close the file function. After each operation on the file, you need to close the file.
	
(4) bool is_open()
	Judge whether the file reading operation object has opened the file. If it is opened successfully, the return value is true,If the opening fails, the return value is false. 

(5) basic_ostream& operator<< ()
	There are many types of arguments to this function, which are used to write the content to be stored to a file.

The operation code for writing a file is as follows (example):

const char FILE_PATH[] = "readTest.txt";

class MyFileStream
{
public:
    MyFileStream()
    {

    }
    ~MyFileStream()
    {

    }
    void writeFileOfOfstream(const string& writeStr)
    {
        ofstream ofs(FILE_PATH,ios_base::app);//Open file as append
        if(!ofs.is_open())
        {
            cout<<"file open fail"<<endl;
            return;
        }
        ofs<<writeStr;
    }
    void readFileOfIfstream(vector<string>& readStrs)
    {
        ifstream ifs(FILE_PATH,ios_base::in);        //read-only

        if(!ifs.is_open())
        {
            cout<<"file open fail"<<endl;
            return;
        }

        while(!ifs.eof())//eof() checks whether the end of the file has been reached
        {
            //string readStr;
            char readStr[100];
            ifs.getline(readStr,100);
            string str(readStr);
            readStrs.emplace_back(str);
        }
        ifs.close();
    }
};
int main()
{
        MyFileStream  myFileStream;
        vector<string> readStrs;
        myFileStream.readFileOfIfstream(readStrs);
        for(auto data:readStrs)
        {
            cout<<data<<endl;
            myFileStream.writeFileOfOfstream(data);
        }
}

Before writing files:

After writing the file:

summary

The above is what I want to talk about today. This article only briefly introduces the use of C + + for file read and write operations. If the above content is wrong, I hope you can correct it!!

Keywords: C++

Added by dvdflashbacks on Sat, 11 Dec 2021 07:02:35 +0200