第 14 節

File operations

0瀏覽次數0訪問次數--跳出率--平均停留

File operations

The data generated during program execution is all temporary data; once the program finishes running, it will all be released.

Data can be persisted through files.

In C++, file operations require including the header file ==< fstream >==

File types are divided into two categories:

  1. Text Files - Files are stored in the computer as text in ASCII format.
  2. Binary files - Files are stored in binary form on the computer, and users generally cannot read them directly.

Three major categories of file operations:

  1. ofstream:write operation
  2. ifstream: read operation
  3. fstream : read and write operations

text file

write file

The steps for writing files are as follows:

  1. Include header files.
    #include <fstream>
  2. Create a stream object
    ofstream ofs;
  3. Open File

ofs.open("file path", open mode);

  1. Write data

ofs << "data to be written";

  1. Closing a file.
    ofs.close();

File open method:

Open WithExplanation
ios::inOpen a file for reading.
ios::outOpen file for writing
ios::ateInitial position: End of file
ios::appWriting files in append mode
ios::truncDelete the file if it exists, then create it.
ios::binaryBinary mode

Note: File opening methods can be used in combination with each other, utilizing I18N_PROTECTED_0.|operator

For example: write a file in binary mode ios::binary|ios:: out`

Example:

#include <fstream>

void test01()
{
    ofstream ofs;
    ofs.open("test.txt", ios::out);

    ofs << "姓名:张三" << endl;
    ofs << "性别:男" << endl;
    ofs << "年龄:18" << endl;

    ofs.close();
}

int main() {
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。

    test01();


    // 返回 0 表示程序正常结束。
    return 0;
}

Run/Observation Result: After running, the example file will be written to the current working directory. You can use cat 文件名 to view the written content.

Summary:

  • File operations must include the header file fstream.
  • Reading files can be accomplished using the ofstream or fstream classes.
  • When opening a file, you need to specify both the path to the file and the mode in which it will be accessed.
  • Use << to write data to the file.
  • After completing the operation, close the file.

read file

Reading files follows steps similar to writing files, but there are relatively more methods available for reading operations.

The steps to read the file are as follows:

  1. Include header files.
    #include <fstream>
  2. Create a stream object
    ifstream ifs;
  3. Open the file and check if the file was opened successfully.

ifs.open("file path", open mode);

  1. Read data

Four ways to read

  1. Closing a file.
    ifs.close();

Example:

#include <fstream>
#include <string>
void test01()
{
    ifstream ifs;
    ifs.open("test.txt", ios::in);

    if (!ifs.is_open())
    {
        cout << "文件打开失败" << endl;
        return;
    }

    //第一种方式
    //char buf[1024] = { 0 };
    //while (ifs >> buf)
    //{
    //  cout << buf << endl;
    //}

    //第二种
    //char buf[1024] = { 0 };
    //while (ifs.getline(buf,sizeof(buf)))
    //{
    //  cout << buf << endl;
    //}

    //第三种
    //string buf;
    //while (getline(ifs, buf))
    //{
    //  cout << buf << endl;
    //}

    char c;
    while ((c = ifs.get()) != EOF)
    {
        cout << c;
    }

    ifs.close();

}

int main() {

    test01();


    return 0;
}

Run/Observe Results: Before running, ensure the corresponding example files exist in the current working directory. The program will print the file content or read results as intended by its reading logic.

Summary:

  • To read files, you can utilize the ifstream or fstream classes.
  • Utilizing the is_open function can determine whether or not the file has been opened successfully.
  • close the file

binary file

Perform file read/write operations in binary format.

The open mode should be specified as ==ios::binary==.

write file

Writing files in binary mode mainly utilizes stream objects to call the write member function.

Function prototype: ostream& write(const char * buffer,int len);

Parameter explanation: The character pointer 'buffer' points to a storage space in memory. 'len' specifies the number of bytes to be read or written.

Example:

#include <fstream>
#include <string>

class Person
{
public:
    char m_Name[64];
    int m_Age;
};

//二进制文件  写文件
void test01()
{
    //1、包含头文件

    //2、创建输出流对象
    ofstream ofs("person.txt", ios::out | ios::binary);
    
    //3、打开文件
    //ofs.open("person.txt", ios::out | ios::binary);

    Person p = {"张三"  , 18};

    //4、写文件
    ofs.write((const char *)&p, sizeof(p));

    //5、关闭文件
    ofs.close();
}

int main() {

    test01();


    return 0;
}

Run/Observation Result: After running, the example file will be written to the current working directory. You can use cat 文件名 to view the written content.

Summary:

  • File output stream objects can write data in binary mode using the write function.

read file

Reading files in binary mode mainly uses the stream object's member function read.

Function prototype: istream& read(char *buffer,int len);

Parameter explanation: The character pointer 'buffer' points to a storage space in memory. 'len' specifies the number of bytes to be read or written.

Example:

#include <fstream>
#include <string>

class Person
{
public:
    char m_Name[64];
    int m_Age;
};

void test01()
{
    ifstream ifs("person.txt", ios::in | ios::binary);
    if (!ifs.is_open())
    {
        cout << "文件打开失败" << endl;
    }

    Person p;
    ifs.read((char *)&p, sizeof(p));

    cout << "姓名: " << p.m_Name << " 年龄: " << p.m_Age << endl;
}

int main() {
    // 程序从 main 函数开始执行,下面的语句会按顺序运行。

    test01();


    // 返回 0 表示程序正常结束。
    return 0;
}

Run/Observe Results: Before running, ensure the corresponding example files exist in the current working directory. The program will print the file content or read results as intended by its reading logic.

  • A file input stream object can use the read function to read data in binary mode.
音乐页