C++中的常见I/O方式

打印 上一主题 下一主题

主题 521|帖子 521|积分 1563

目录
摘要
1. 标准输入输出(Standard I/O)
2. 文件输入输出(File I/O)
3. 字符串流(String Stream)
4. 低级文件I/O(Low-level File I/O)
5. 内存映射文件(Memory-Mapped File I/O)
6. 网络I/O(Network I/O)
服务器端
客户端

摘要

C++中的输入输出操作(I/O)方式多种多样,从简单的标准I/O到复杂的内存映射文件和网络I/O。每一种的用法都有其特别之处,下面会分别用代码的方式来简单先容一些用法,可以根据自己项目所需来选择符合的I/O方式可以进步我们项目开发的服从。
1. 标准输入输出(Standard I/O)

标准输入输出用于与控制台举行交互。
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <sstream>
  5. using namespace std;
  6. struct Student {
  7.     string name;
  8.     int age;
  9.     vector<int> grades;
  10.     void display() const {
  11.         cout << "Name: " << name << ", Age: " << age << ", Grades: ";
  12.         for (int grade : grades) {
  13.             cout << grade << " ";
  14.         }
  15.         cout << endl;
  16.     }
  17. };
  18. int main() {
  19.     vector<Student> students;
  20.     string input;
  21.     cout << "Enter student information (name age grades), type 'end' to stop:" << endl;
  22.     while (true) {
  23.         getline(cin, input);
  24.         if (input == "end") break;
  25.         istringstream iss(input);
  26.         Student student;
  27.         iss >> student.name >> student.age;
  28.         int grade;
  29.         while (iss >> grade) {
  30.             student.grades.push_back(grade);
  31.         }
  32.         students.push_back(student);
  33.     }
  34.     cout << "Entered students:" << endl;
  35.     for (const Student& student : students) {
  36.         student.display();
  37.     }
  38.     return 0;
  39. }
复制代码
2. 文件输入输出(File I/O)

文件I/O操作允许将数据存储到文件中或从文件中读取。
  1. #include <fstream>
  2. #include <iostream>
  3. #include <vector>
  4. #include <string>
  5. using namespace std;
  6. struct Employee {
  7.     string name;
  8.     int id;
  9.     double salary;
  10.     void display() const {
  11.         cout << "Name: " << name << ", ID: " << id << ", Salary: " << salary << endl;
  12.     }
  13. };
  14. int main() {
  15.     vector<Employee> employees = {
  16.         {"Aoteman", 1, 50000},
  17.         {"AotemanDaddy", 2, 60000},
  18.         {"AotemanMami", 3, 70000}
  19.     };
  20.     ofstream outFile("employees.dat", ios::binary);
  21.     if (!outFile) {
  22.         cerr << "Error opening file for writing" << endl;
  23.         return 1;
  24.     }
  25.     for (const Employee& emp : employees) {
  26.         outFile.write((char*)&emp, sizeof(Employee));
  27.     }
  28.     outFile.close();
  29.     vector<Employee> readEmployees;
  30.     ifstream inFile("employees.dat", ios::binary);
  31.     if (!inFile) {
  32.         cerr << "Error opening file for reading" << endl;
  33.         return 1;
  34.     }
  35.     Employee emp;
  36.     while (inFile.read((char*)&emp, sizeof(Employee))) {
  37.         readEmployees.push_back(emp);
  38.     }
  39.     inFile.close();
  40.     cout << "Read employees:" << endl;
  41.     for (const Employee& emp : readEmployees) {
  42.         emp.display();
  43.     }
  44.     return 0;
  45. }
复制代码
3. 字符串流(String Stream)

字符串流用于处置惩罚内存中的字符串流。
  1. #include <sstream>
  2. #include <iostream>
  3. #include <vector>
  4. #include <string>
  5. using namespace std;
  6. struct Product {
  7.     string name;
  8.     double price;
  9.     int quantity;
  10.     void display() const {
  11.         cout << "Name: " << name << ", Price: " << price << ", Quantity: " << quantity << endl;
  12.     }
  13. };
  14. int main() {
  15.     vector<Product> products = {
  16.         {"Apple", 999.99, 5},
  17.         {"HuaWei", 699.99, 10},
  18.         {"SanXing", 299.99, 7}
  19.     };
  20.     ostringstream oss;
  21.     for (const Product& prod : products) {
  22.         oss << prod.name << " " << prod.price << " " << prod.quantity << "\n";
  23.     }
  24.     string productData = oss.str();
  25.     cout << "Serialized products:\n" << productData;
  26.     vector<Product> parsedProducts;
  27.     istringstream iss(productData);
  28.     string name;
  29.     double price;
  30.     int quantity;
  31.     while (iss >> name >> price >> quantity) {
  32.         parsedProducts.push_back({name, price, quantity});
  33.     }
  34.     cout << "Parsed products:" << endl;
  35.     for (const Product& prod : parsedProducts) {
  36.         prod.display();
  37.     }
  38.     return 0;
  39. }
复制代码
4. 低级文件I/O(Low-level File I/O)

低级文件I/O使用系统调用来举行文件操作,提供了更高的灵活性和控制力。
  1. #include <fcntl.h>
  2. #include <unistd.h>
  3. #include <iostream>
  4. #include <vector>
  5. #include <cstring>
  6. using namespace std;
  7. struct Record {
  8.     char name[20];
  9.     int value;
  10.     void display() const {
  11.         cout << "Name: " << name << ", Value: " << value << endl;
  12.     }
  13. };
  14. int main() {
  15.     vector<Record> records = {
  16.         {"Record1", 100},
  17.         {"Record2", 200},
  18.         {"Record3", 300}
  19.     };
  20.     int fd = open("records.dat", O_WRONLY | O_CREAT, 0644);
  21.     if (fd == -1) {
  22.         cerr << "Error opening file for writing" << endl;
  23.         return 1;
  24.     }
  25.     for (const Record& rec : records) {
  26.         write(fd, &rec, sizeof(Record));
  27.     }
  28.     close(fd);
  29.     vector<Record> readRecords;
  30.     fd = open("records.dat", O_RDONLY);
  31.     if (fd == -1) {
  32.         cerr << "Error opening file for reading" << endl;
  33.         return 1;
  34.     }
  35.     Record rec;
  36.     while (read(fd, &rec, sizeof(Record)) > 0) {
  37.         readRecords.push_back(rec);
  38.     }
  39.     close(fd);
  40.     cout << "Read records:" << endl;
  41.     for (const Record& rec : readRecords) {
  42.         rec.display();
  43.     }
  44.     return 0;
  45. }
复制代码
5. 内存映射文件(Memory-Mapped File I/O)

内存映射文件将文件内容映射到历程的地址空间。
  1. #include <sys/mman.h>
  2. #include <fcntl.h>
  3. #include <unistd.h>
  4. #include <iostream>
  5. #include <cstring>
  6. using namespace std;
  7. struct Data {
  8.     char text[50];
  9.     int number;
  10.     void display() const {
  11.         cout << "Text: " << text << ", Number: " << number << endl;
  12.     }
  13. };
  14. int main() {
  15.     int fd = open("mmapdata.dat", O_RDWR | O_CREAT, 0644);
  16.     if (fd == -1) {
  17.         cerr << "Error opening file" << endl;
  18.         return 1;
  19.     }
  20.     Data data = {"Memory-mapped file example", 42};
  21.     write(fd, &data, sizeof(Data));
  22.     size_t filesize = sizeof(Data);
  23.     Data *map = static_cast<Data*>(mmap(0, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
  24.     if (map == MAP_FAILED) {
  25.         cerr << "Error mapping file" << endl;
  26.         close(fd);
  27.         return 1;
  28.     }
  29.     // 修改映射区域内容
  30.     strcpy(map->text, "Updated text");
  31.     map->number = 99;
  32.     // 取消映射
  33.     munmap(map, filesize);
  34.     close(fd);
  35.     // 读取文件内容
  36.     fd = open("mmapdata.dat", O_RDONLY);
  37.     if (fd == -1) {
  38.         cerr << "Error opening file" << endl;
  39.         return 1;
  40.     }
  41.     Data readData;
  42.     read(fd, &readData, sizeof(Data));
  43.     close(fd);
  44.     cout << "Read data:" << endl;
  45.     readData.display();
  46.     return 0;
  47. }
复制代码
6. 网络I/O(Network I/O)

网络I/O用于通过网络举行数据传输,涉及到套接字编程。
服务器端

  1. #include <sys/socket.h>
  2. #include <netinet/in.h>
  3. #include <unistd.h>
  4. #include <iostream>
  5. #include <cstring>
  6. using namespace std;
  7. int main() {
  8.     int server_fd = socket(AF_INET, SOCK_STREAM, 0);
  9.     if (server_fd == -1) {
  10.         cerr << "Error creating socket" << endl;
  11.         return 1;
  12.     }
  13.     struct sockaddr_in server_addr;
  14.     server_addr.sin_family = AF_INET;
  15.     server_addr.sin_port = htons(9090);
  16.     server_addr.sin_addr.s_addr = INADDR_ANY;
  17.     if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
  18.         cerr << "Error binding socket" << endl;
  19.         close(server_fd);
  20.         return 1;
  21.     }
  22.     if (listen(server_fd, 5) == -1) {
  23.         cerr << "Error listening on socket" << endl;
  24.         close(server_fd);
  25.         return 1;
  26.     }
  27.     cout << "Server listening on port 9090..." << endl;
  28.     int client_fd = accept(server_fd, nullptr, nullptr);
  29.     if (client_fd == -1) {
  30.         cerr << "Error accepting connection" << endl;
  31.         close(server_fd);
  32.         return 1;
  33.     }
  34.     char buffer[256];
  35.     ssize_t bytesReceived = recv(client_fd, buffer, sizeof(buffer) - 1, 0);
  36.     if (bytesReceived == -1) {
  37.         cerr << "Error receiving data" << endl;
  38.         close(client_fd);
  39.         close(server_fd);
  40.         return 1;
  41.     }
  42.     buffer[bytesReceived] = '\0';
  43.     cout << "Received from client: " << buffer << endl;
  44.     const char *response = "Message received";
  45.     send(client_fd, response, strlen(response), 0);
  46.     close(client_fd);
  47.     close(server_fd);
  48.     return 0;
  49. }
复制代码
客户端

  1. #include <sys/socket.h>
  2. #include <netinet/in.h>
  3. #include <arpa/inet.h>
  4. #include <unistd.h>
  5. #include <iostream>
  6. #include <cstring>
  7. using namespace std;
  8. int main() {
  9.     int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  10.     if (sockfd == -1) {
  11.         cerr << "Error creating socket" << endl;
  12.         return 1;
  13.     }
  14.     struct sockaddr_in server_addr;
  15.     server_addr.sin_family = AF_INET;
  16.     server_addr.sin_port = htons(9090);
  17.     server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  18.     if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
  19.         cerr << "Error connecting to server" << endl;
  20.         close(sockfd);
  21.         return 1;
  22.     }
  23.     const char *msg = "Hello, server!";
  24.     send(sockfd, msg, strlen(msg), 0);
  25.     char buffer[256];
  26.     ssize_t bytesReceived = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
  27.     if (bytesReceived == -1) {
  28.         cerr << "Error receiving data" << endl;
  29.     } else {
  30.         buffer[bytesReceived] = '\0';
  31.         cout << "Received from server: " << buffer << endl;
  32.     }
  33.     close(sockfd);
  34.     return 0;
  35. }
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

农妇山泉一亩田

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表