How to read and write files in c++

青灯夜游
Release: 2023-01-07 11:41:08
Original
24637 people have browsed it

c Methods for reading and writing files: 1. Use the ">>" and "<<" operators; 2. Use "istream::read()" and " ostream::write()" method; 3. Use the "istream::get()" and "ostream::put()" member methods.

How to read and write files in c++

The operating environment of this tutorial: Windows 7 system, C 17 version, Dell G3 computer.

Method 1: C >> and << read and write text files

The fstream or ifstream class is responsible for implementing the file Reading, they all overload the >> output stream operator internally; similarly, the fstream and ofstream classes are responsible for writing files, and they also internally <code>&lt ;< The output stream operator is overloaded.

So, when an fstream or ifstream class object opens a file (usually using ios::in as the opening mode), you can directly use the >> input stream operator to read the characters stored in the file ( or string); when an fstream or ofstream class object opens a file (usually using ios::out as the opening mode), you can directly use the << output stream operator to write characters (or strings) to the file.

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    int x,sum=0;
    ifstream srcFile("in.txt", ios::in); //以文本模式打开in.txt备读
    if (!srcFile) { //打开失败
        cout << "error opening source file." << endl;
        return 0;
    }
    ofstream destFile("out.txt", ios::out); //以文本模式打开out.txt备写
    if (!destFile) {
        srcFile.close(); //程序结束前不能忘记关闭以前打开过的文件
        cout << "error opening destination file." << endl;
        return 0;
    }
    //可以像用cin那样用ifstream对象
    while (srcFile >> x) {
        sum += x;
        //可以像 cout 那样使用 ofstream 对象
        destFile << x << " ";
    }
    cout << "sum:" << sum << endl;
    destFile.close();
    srcFile.close();
    return 0;
}
Copy after login

Before executing this program, you must manually create an in.txt file in the same directory as the program source file. Assume that the string stored internally is:

10 20 30 40 50
Copy after login

After creation, execute The execution result of the program is:

sum:150
Copy after login

At the same time, an out.txt file will be generated in the same directory as the in.txt file. The characters stored in it are exactly the same as the in.txt file. Readers can open the file by themselves. Check.

It is not difficult to understand by analyzing the execution results of the program. For the "10 20 30 40 50" string in the in.txt file, the srcFile object will sequentially convert "10", "20", "30", "40" and "50" are read out, parsed into int type integers 10, 20, 30, 40, 50 and assigned to x, and the addition operation with sum is completed at the same time.

Similarly, for each integer x read and parsed from the in.txt file, the destFile object will parse it into the corresponding string unchanged (such as the integer 10 parsed into a string " 10"), and then write it to the out.txt file together with the " " space character.

Method 2: C read() and write() to read and write binary files

C ostream::write() method Write files

The write() member method of ofstream and fstream is actually inherited from the ostream class. Its function is to write the count bytes pointed to by the buffer in the memory to the file. The basic format is as follows:

ostream & write(char* buffer, int count);
Copy after login

Among them, buffer is used to specify the starting position of the binary data to be written to the file; count is used to specify the number of bytes to be written.

In other words, this method can be called by the cout object of the ostream class, and is often used to output strings to the screen. At the same time, it can also be called by ofstream or fstream objects to write a specified number of binary data to a file.

At the same time, this method will return an object in the form of a reference that acts on the function. For example, the return value of the obj.write() method is a reference to the obj object.

One thing to note is that the write() member method writes a number of bytes to the file, but when calling the write() function, the specific location where these bytes are written in the file is not specified. In fact, the write() method writes binary data from the location pointed by the file write pointer. The so-called file write pointer is a variable maintained internally by the ofstream or fstream object. When the file is first opened, the file write pointer points to the beginning of the file (if it is opened in ios::app mode, it points to the end of the file). Use write( ) method writes n bytes, and the position pointed by the write pointer moves backward by n bytes.

The following program demonstrates how to write student information to a file in binary form:

#include <iostream>
#include <fstream>
using namespace std;
class CStudent
{
public:
    char szName[20];
    int age;
};
int main()
{
    CStudent s;
    ofstream outFile("students.dat", ios::out | ios::binary);
    while (cin >> s.szName >> s.age)
        outFile.write((char*)&s, sizeof(s));
    outFile.close();
    return 0;
}
Copy after login

Input:

Tom 60↙
Jack 80↙
Jane 40↙
^Z↙
Copy after login

Among them, represents the output newline symbol, ^Z means entering the Ctrl Z key combination to end the input.

After executing the program, a students.dat file will be automatically generated, which contains 72 bytes of data. If you open this file with "Notepad", you may see the following garbled characters:

Tom 烫烫烫烫烫烫烫烫<   Jack 烫烫烫烫烫烫烫蘌   Jane 烫烫烫烫烫烫烫?
Copy after login

It is worth mentioning that the opening mode of the file specified in line 13 of the program is ios::out | ios::binary, that is, it is opened in binary writing mode. On the Windows platform, it is very necessary to open the file in binary mode, otherwise an error may occur.

Also, line 15 writes the s object to the file. The address of s is the address of the memory buffer to be written to the file, but &s is not of char * type, so forced type conversion is required; line 16, the file must be closed after use, otherwise the content of the file may be incomplete after the program ends. .

C istream::read() method reads files

The read() method of ifstream and fstream actually inherits from the istream class, and its function is exactly the same as write() The opposite method is to read count bytes of data from the file. The syntax format of this method is as follows:

istream & read(char* buffer, int count);
Copy after login

其中,buffer 用于指定读取字节的起始位置,count 指定读取字节的个数。同样,该方法也会返回一个调用该方法的对象的引用。

和 write() 方法类似,read() 方法从文件读指针指向的位置开始读取若干字节。所谓文件读指针,可以理解为是 ifstream 或 fstream 对象内部维护的一个变量。文件刚打开时,文件读指针指向文件的开头(如果以 ios::app 方式打开,则指向文件末尾),用 read() 方法读取 n 个字节,读指针指向的位置就向后移动 n 个字节。因此,打开一个文件后连续调用 read() 方法,就能将整个文件的内容读取出来。

通过执行 write() 方法的示例程序,我们将 3 个学生的信息存储到了 students.dat 文件中,下面程序演示了如何使用 read() 方法将它们读取出来:

#include <iostream>
#include <fstream>
using namespace std;
class CStudent
{
public:
    char szName[20];
    int age;
};
int main()
{
    CStudent s;       
    ifstream inFile("students.dat",ios::in|ios::binary); //二进制读方式打开
    if(!inFile) {
        cout << "error" <<endl;
        return 0;
    }
    while(inFile.read((char *)&s, sizeof(s))) { //一直读到文件结束
        cout << s.szName << " " << s.age << endl;   
    }
    inFile.close();
    return 0;
}
Copy after login

程序的输出结果是:

Tom 60
Jack 80
Jane 40
Copy after login

注意,程序中第 18 行直接将 read() 方法作为 while 循环的判断条件,这意味着,read() 方法会一直读取到文件的末尾,将所有字节全部读取完毕,while 循环才会终止。

方法3:C++ get()和put()读写文件

在某些特殊的场景中,我们可能需要逐个读取文件中存储的字符,或者逐个将字符存储到文件中。这种情况下,就可以调用 get() 和 put() 成员方法实现。

C++ ostream::put()成员方法

我们知道,fstream 和 ofstream 类继承自 ostream 类,因此 fstream 和 ofstream 类对象都可以调用 put() 方法。

当 fstream 和 ofstream 文件流对象调用 put() 方法时,该方法的功能就变成了向指定文件中写入单个字符。put() 方法的语法格式如下:

ostream& put (char c);
Copy after login

其中,c 用于指定要写入文件的字符。该方法会返回一个调用该方法的对象的引用形式。例如,obj.put() 方法会返回 obj 这个对象的引用。

举个例子:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    char c;
    //以二进制形式打开文件
    ofstream outFile("out.txt", ios::out | ios::binary);
    if (!outFile) {
        cout << "error" << endl;
        return 0;
    }
    while (cin >> c) {
        //将字符 c 写入 out.txt 文件
        outFile.put(c);
    }
    outFile.close();
    return 0;
}
Copy after login

执行程序,输入:

https://www.php.cn/↙
^Z↙
Copy after login

其中,表示输入换行符;^ZCtrl+Z 的组合键,表示输入结束。

由此,程序中通过执行 while 循环,会将 "https://www.php.cn/" 字符串的字符逐个复制给变量 c,并逐个写入到 out.txt 文件。

注意,由于文件存放在硬盘中,硬盘的访问速度远远低于内存。如果每次写一个字节都要访问硬盘,那么文件的读写速度就会慢得不可忍受。因此,操作系统在接收到 put() 方法写文件的请求时,会先将指定字符存储在一块指定的内存空间中(称为文件流输出缓冲区),等刷新该缓冲区(缓冲区满、关闭文件、手动调用 flush() 方法等,都会导致缓冲区刷新)时,才会将缓冲区中存储的所有字符“一股脑儿”全写入文件。

C++ istream::get()成员方法

和 put() 成员方法的功能相对的是 get() 方法,其定义在 istream 类中,借助 cin.get() 可以读取用户输入的字符。在此基础上,fstream 和 ifstream 类继承自 istream 类,因此 fstream 和 ifstream 类的对象也能调用 get() 方法。

当 fstream 和 ifstream 文件流对象调用 get() 方法时,其功能就变成了从指定文件中读取单个字符(还可以读取指定长度的字符串)。值得一提的是,get() 方法的语法格式有很多(请猛击这里了解详情),这里仅介绍最常用的 2 种:

int get();
istream& get (char& c);
Copy after login

其中,第一种语法格式的返回值就是读取到的字符,只不过返回的是它的 ASCII 码,如果碰到输入的末尾,则返回值为 EOF。第二种语法格式需要传递一个字符变量,get() 方法会自行将读取到的字符赋值给这个变量。

本节前面在讲解 put() 方法时,生成了一个 out.txt 文件,下面的样例演示了如何通过 get() 方法逐个读取 out.txt 文件中的字符:

#include <iostream>
#include <fstream>
using namespace std;
int main()
{
    char c;
    //以二进制形式打开文件
    ifstream inFile("out.txt", ios::out | ios::binary);
    if (!inFile) {
        cout << "error" << endl;
        return 0;
    }
    while ( (c=inFile.get())&&c!=EOF )   //或者 while(inFile.get(c)),对应第二种语法格式
    {
        cout << c ;
    }
    inFile.close();
    return 0;
}
Copy after login

程序执行结果为:

https://www.php.cn/
Copy after login

注意,和 put() 方法一样,操作系统在接收到 get() 方法的请求后,哪怕只读取一个字符,也会一次性从文件中将很多数据(通常至少是 512 个字节,因为硬盘的一个扇区是 512 B)读到一块内存空间中(可称为文件流输入缓冲区),这样当读取下一个字符时,就不需要再访问硬盘中的文件,直接从该缓冲区中读取即可。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of How to read and write files in c++. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!