赞
踩
目录
4. 低级文件I/O(Low-level File I/O)
5. 内存映射文件(Memory-Mapped File I/O)
C++中的输入输出操作(I/O)方式多种多样,从简单的标准I/O到复杂的内存映射文件和网络I/O。每一种的用法都有其特别之处,下面会分别用代码的方式来简单介绍一些用法,可以根据自己项目所需来选择合适的I/O方式可以提高我们项目开发的效率。
标准输入输出用于与控制台进行交互。
- #include <iostream>
- #include <vector>
- #include <string>
- #include <sstream>
- using namespace std;
-
- struct Student {
- string name;
- int age;
- vector<int> grades;
-
- void display() const {
- cout << "Name: " << name << ", Age: " << age << ", Grades: ";
- for (int grade : grades) {
- cout << grade << " ";
- }
- cout << endl;
- }
- };
-
- int main() {
- vector<Student> students;
- string input;
- cout << "Enter student information (name age grades), type 'end' to stop:" << endl;
- while (true) {
- getline(cin, input);
- if (input == "end") break;
-
- istringstream iss(input);
- Student student;
- iss >> student.name >> student.age;
- int grade;
- while (iss >> grade) {
- student.grades.push_back(grade);
- }
- students.push_back(student);
- }
-
- cout << "Entered students:" << endl;
- for (const Student& student : students) {
- student.display();
- }
-
- return 0;
- }
文件I/O操作允许将数据存储到文件中或从文件中读取。
- #include <fstream>
- #include <iostream>
- #include <vector>
- #include <string>
- using namespace std;
-
- struct Employee {
- string name;
- int id;
- double salary;
-
- void display() const {
- cout << "Name: " << name << ", ID: " << id << ", Salary: " << salary << endl;
- }
- };
-
- int main() {
- vector<Employee> employees = {
- {"Aoteman", 1, 50000},
- {"AotemanDaddy", 2, 60000},
- {"AotemanMami", 3, 70000}
- };
-
- ofstream outFile("employees.dat", ios::binary);
- if (!outFile) {
- cerr << "Error opening file for writing" << endl;
- return 1;
- }
- for (const Employee& emp : employees) {
- outFile.write((char*)&emp, sizeof(Employee));
- }
- outFile.close(
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。