12、C++面向程序设计:C++流、IO操作

1、C++流的类库

C++流的类库是C++标准库中的一个重要组成部分,提供了用于输入和输出的通用流操作接口和功能。C++标准库中的流类库包括了iostream、fstream、sstream和iomanip四个主要的类库。

(1)iostream:iostream类库提供了用于标准输入和输出的流操作接口。它定义了两个主要的类:istream用于输入(如键盘输入),ostream用于输出(如屏幕输出)。iostream类库还定义了一系列的操纵符(manipulator),用于控制输出格式,如setw、setprecision等。

(2)fstream:fstream类库提供了用于文件输入和输出的流操作接口。它定义了三个主要的类:ifstream用于文件输入,ofstream用于文件输出,以及fstream用于文件输入和输出。使用fstream类库,可以方便地读取和写入文件中的数据。

(3)sstream:sstream类库提供了用于内存字符串输入和输出的流操作接口。它定义了两个主要的类:istringstream用于字符串输入,ostringstream用于字符串输出,以及stringstream用于字符串输入和输出。使用sstream类库,可以将字符串作为输入源或输出目标,方便地处理字符串数据。

(4)iomanip:iomanip类库提供了用于流的格式控制的操纵符(manipulator)。它定义了一系列的操纵符,用于控制输出的格式,如设置字段宽度(setw)、设置精度(setprecision)、设置对齐方式(setfill、setiosflags)等。使用iomanip类库,可以方便地控制输出的格式。

C++流的类库提供了一种方便和统一的方式来处理输入和输出。通过使用流操作符(如>>和<<),可以将数据从流中读取或写入到流中,而无需关心底层的具体实现细节。流类库提供了丰富的功能,如格式化输入输出、文件读写、字符串处理等,可以满足各种不同的需求。

在使用流类库时,需要包含相应的头文件,如<iostream>、<fstream>、<sstream>和<iomanip>。使用流类库时,可以通过重载流操作符(<<和>>)来自定义对象的输入和输出方式,以及通过调用类的成员函数来进行相应的操作,如读取和写入数据。同时,流类库也提供了一些成员函数和操纵符,用于控制流的状态和格式。

2、C++输出流

C++输出流是C++流类库中的一部分,用于将数据输出到不同的目标,如屏幕、文件或字符串。下面是五个通俗易懂的例子,展示了C++输出流的不同用法:

(1)输出到屏幕:

#include <iostream>

using namespace std;

int main() {

    int num = 10;

    float pi = 3.14159;

    string name = “Alice”;

    

    cout << “Number: ” << num << endl;

    cout << “Pi: ” << pi << endl;

    cout << “Name: ” << name << endl;

    

    return 0;

}

这个例子演示了将不同类型的数据输出到屏幕,并使用endl操纵符来换行。

2. 输出到文件:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    ofstream file(“output.txt”);

    

    if (file.is_open()) {

        file << “Hello, file!” << endl;

        file << “This is a line in the file.” << endl;

        file.close();

        cout << “File written successfully.” << endl;

    } else {

        cout << “Unable to open file.” << endl;

    }

    

    return 0;

}

这个例子演示了将文本数据写入到文件中。首先创建一个ofstream对象,然后使用该对象的<<操作符将数据写入到文件中。

(3)格式化输出:

#include <iostream>

#include <iomanip>

using namespace std;

int main() {

    float pi = 3.14159;

    

    cout << fixed << setprecision(2) << “Pi: ” << pi << endl;

    cout << “Hexadecimal: ” << hex << showbase << 42 << endl;

    cout << “Binary: ” << bitset<8>(42) << endl;

    

    return 0;

}

这个例子演示了使用iomanip类库中的操纵符来格式化输出。通过设置fixed和setprecision(2),可以保留两位小数;使用hex和showbase,可以输出十六进制数,并显示前缀;使用bitset,可以将整数转换为二进制字符串。

(4)输出到字符串:

#include <iostream>

#include <sstream>

using namespace std;

int main() {

    ostringstream oss;

    int num = 42;

    float pi = 3.14159;

    string name = “Bob”;

    

    oss << “Number: ” << num << endl;

    oss << “Pi: ” << pi << endl;

    oss << “Name: ” << name << endl;

    

    string output = oss.str();

    cout << output;

    

    return 0;

}

这个例子演示了使用ostringstream类库将数据输出到字符串。首先创建一个ostringstream对象,然后使用该对象的<<操作符将数据写入到字符串流中。最后,使用ostringstream的str()函数将字符串流中的数据取出,并保存到一个字符串中。

(5) 输出到多个目标:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    ofstream file(“output.txt”);

    

    if (file.is_open()) {

        streambuf* coutbuf = cout.rdbuf();

        cout.rdbuf(file.rdbuf());

        

        cout << “Hello, file!” << endl;

        cout.rdbuf(coutbuf);

        

        cout << “Hello, screen!” << endl;

        

        file.close();

        cout << “File written successfully.” << endl;

    } else {

        cout << “Unable to open file.” << endl;

    }

    

    return 0;

}

这个例子演示了将数据同时输出到文件和屏幕。通过保存cout的缓冲区指针,并将其替换为文件流的缓冲区指针,可以将后续的输出重定向到文件。最后,将cout的缓冲区指针恢复为原来的值,可以继续在屏幕上输出。

3、C++流状态

C++流状态表示流的当前状态,包括读取状态和写入状态。通过检查流的状态,我们可以判断流是否正常工作或遇到了错误。C++提供了几个成员函数来获取和设置流的状态,如good()、fail()、bad()和eof()。下面是三个通俗易懂的例子,展示了C++流状态的不同用法:

(1)检查读取状态:

#include <iostream>

using namespace std;

int main() {

    int num;

    

    cout << “Enter a number: “;

    cin >> num;

    

    if (cin.good()) {

        cout << “Read successful!” << endl;

    } else {

        cout << “Read failed!” << endl;

    }

    

    return 0;

}

这个例子演示了使用cin的good()函数来检查读取状态。如果读取成功,即用户输入了一个合法的整数,就输出”Read successful!”;否则输出”Read failed!”。

(2)检查写入状态:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    ofstream file(“output.txt”);

    

    if (file.is_open()) {

        file << “Hello, file!”;

        

        if (file.good()) {

            cout << “Write successful!” << endl;

        } else {

            cout << “Write failed!” << endl;

        }

        

        file.close();

    } else {

        cout << “Unable to open file.” << endl;

    }

    

    return 0;

}

这个例子演示了使用file的good()函数来检查写入状态。如果写入成功,即内容成功写入到文件中,就输出”Write successful!”;否则输出”Write failed!”。

(3)捕获和处理错误:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    ifstream file(“nonexistent.txt”);

    

    if (file.fail()) {

        cerr << “Unable to open file.” << endl;

    } else {

        string line;

        

        while (getline(file, line)) {

            cout << line << endl;

        }

        

        file.close();

    }

    

    return 0;

}

这个例子演示了使用file的fail()函数来检查文件打开错误。如果文件打开失败,即文件不存在或无法打开,就使用cerr输出错误信息;否则读取文件内容并输出到屏幕。

这些例子展示了C++流状态的不同用法,包括检查读取状态、写入状态以及处理错误。通过检查流的状态,我们可以根据需要采取适当的操作,如继续读取、写入或处理错误。在实际应用中,我们可以根据流的状态来决定程序的执行路径,以保证程序的正确性和可靠性。

4、C++文件操作

C++文件操作是指在C++程序中对文件进行读取、写入、修改和删除等操作。常用的文件操作类包括ifstream、ofstream和fstream,它们分别用于读取、写入和读取和写入文件。下面是十个通俗易懂的例子,展示了C++文件操作的不同用法:

(1)打开文件并写入内容:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    ofstream file(“output.txt”);

    

    if (file.is_open()) {

        file << “Hello, file!”;

        file.close();

        cout << “文件创建并写入成功。” << endl;

    } else {

        cout << “无法创建文件。” << endl;

    }

    

    return 0;

}

此示例使用ofstream类创建一个文件,并将字符串”Hello, file!”写入文件中。如果文件成功创建并写入内容,将输出”文件创建并写入成功。”,否则输出”无法创建文件。”。

(2) 从文件中读取内容并输出到屏幕:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    ifstream file(“input.txt”);

    

    if (file.is_open()) {

        string line;

        

        while (getline(file, line)) {

            cout << line << endl;

        }

        

        file.close();

    } else {

        cout << “无法打开文件。” << endl;

    }

    

    return 0;

}

此示例使用ifstream类打开一个文件,并逐行读取文件内容并输出到屏幕。如果文件成功读取并输出内容,将显示文件内容,否则输出”无法打开文件。”。

(3)检查文件是否存在:

#include <iostream>

#include <fstream>

using namespace std;

bool fileExists(const string& filename) {

    ifstream file(filename);

    return file.good();

}

int main() {

    string filename = “myfile.txt”;

    

    if (fileExists(filename)) {

        cout << “文件存在。” << endl;

    } else {

        cout << “文件不存在。” << endl;

    }

    

    return 0;

}

此示例使用ifstream类检查文件是否存在。如果文件存在,输出”文件存在。”,否则输出”文件不存在。”。

(4)向文件追加内容:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    ofstream file(“output.txt”, ios::app);

    

    if (file.is_open()) {

        file << ” 这是追加的内容。”;

        file.close();

        cout << “内容追加成功。” << endl;

    } else {

        cout << “无法打开文件。” << endl;

    }

    

    return 0;

}

此示例使用ofstream类的ios::app模式向文件追加内容。如果内容成功追加到文件中,输出”内容追加成功。”,否则输出”无法打开文件。”。

(5)复制文件:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    ifstream sourceFile(“source.txt”);

    ofstream destFile(“destination.txt”);

    

    if (sourceFile.is_open() && destFile.is_open()) {

        string line;

        

        while (getline(sourceFile, line)) {

            destFile << line << endl;

        }

        

        sourceFile.close();

        destFile.close();

        cout << “文件复制成功。” << endl;

    } else {

        cout << “无法打开文件。” << endl;

    }

    

    return 0;

}

此示例使用ifstream类和ofstream类将一个文件的内容复制到另一个文件中。如果文件成功复制,输出”文件复制成功。”,否则输出”无法打开文件。”。

(6)删除文件:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    string filename = “file.txt”;

    

    if (remove(filename.c_str()) == 0) {

        cout << “文件删除成功。” << endl;

    } else {

        cout << “无法删除文件。” << endl;

    }

    

    return 0;

}

此示例使用remove函数删除文件。如果文件成功删除,输出”文件删除成功。”,否则输出”无法删除文件。”。

(7)统计文件中的字符数:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    ifstream file(“input.txt”);

    

    if (file.is_open()) {

        int count = 0;

        char ch;

        

        while (file.get(ch)) {

            count++;

        }

        

        file.close();

        cout << “文件中的字符数:” << count << endl;

    } else {

        cout << “无法打开文件。” << endl;

    }

    

    return 0;

}

此示例使用ifstream类打开文件,并统计文件中的字符数。如果文件成功打开,输出文件中的字符数,否则输出”无法打开文件。”。

(8)重命名文件:

#include <iostream>

using namespace std;

int main() {

    string oldFilename = “oldfile.txt”;

    string newFilename = “newfile.txt”;

    

    if (rename(oldFilename.c_str(), newFilename.c_str()) == 0) {

        cout << “文件重命名成功。” << endl;

    } else {

        cout << “无法重命名文件。” << endl;

    }

    

    return 0;

}

此示例使用rename函数对文件进行重命名。如果文件成功重命名,输出”文件重命名成功。”,否则输出”无法重命名文件。”。

(9)读取二进制文件:

#include <iostream>

#include <fstream>

using namespace std;

int main() {

    ifstream file(“binaryfile.bin”, ios::binary);

    

    if (file.is_open()) {

        int value;

        

        while (file.read((char*)&value, sizeof(value))) {

            cout << value << ” “;

        }

        

        file.close();

    } else {

        cout << “无法打开文件。” << endl;

    }

    

    return 0;

}

此示例使用ifstream类以二进制模式读取文件。如果文件成功打开,输出文件中的整数,否则输出”无法打开文件。”。

(10)将字符串写入二进制文件

#include <iostream>

#include <fstream>

#include <string>

int main() {

    std::string str = “Hello, World!”;

    std::ofstream file(“output.bin”, std::ios::binary);

    if (file.is_open()) {

        file.write((char*)&str[0], sizeof(char) * str.length());

        file.close();

        std::cout << “Binary file written successfully.” << std::endl;

    } else {

        std::cerr << “Failed to open binary file.” << std::endl;

    }

    return 0;

}

(11)将结构体写入二进制文件

#include <iostream>

#include <fstream>

struct Person {

    int age;

    float height;

};

int main() {

    Person person;

    person.age = 25;

    person.height = 1.75f;

    std::ofstream file(“output.bin”, std::ios::binary);

    if (file.is_open()) {

        file.write((char*)&person, sizeof(Person));

        file.close();

        std::cout << “Binary file written successfully.” << std::endl;

    } else {

        std::cerr << “Failed to open binary file.” << std::endl;

    }

    return 0;

}

在上述例子中,我们定义了一个结构体Person,该结构体包含两个成员变量age和height。

我们创建一个Person对象person,并给其成员变量赋值。

然后,我们创建一个ofstream对象file,指定打开文件的名称为output.bin,使用std::ios::binary打开文件以二进制模式。

接下来,我们使用file.write()将person对象以二进制形式写入文件。为了将结构体视为一系列字节,我们使用(char*)&person进行类型转换,并使用sizeof(Person)获取要写入的字节数。

最后,我们检查文件是否成功打开,如果成功则关闭文件,并输出相应的信息。否则,输出错误信息。

 

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容