ToB企服应用市场:ToB评测及商务社交产业平台
标题:
C++中的常见I/O方式
[打印本页]
作者:
农妇山泉一亩田
时间:
2024-6-10 10:18
标题:
C++中的常见I/O方式
目录
摘要
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)
标准输入输出用于与控制台举行交互。
#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;
}
复制代码
2. 文件输入输出(File I/O)
文件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();
vector<Employee> readEmployees;
ifstream inFile("employees.dat", ios::binary);
if (!inFile) {
cerr << "Error opening file for reading" << endl;
return 1;
}
Employee emp;
while (inFile.read((char*)&emp, sizeof(Employee))) {
readEmployees.push_back(emp);
}
inFile.close();
cout << "Read employees:" << endl;
for (const Employee& emp : readEmployees) {
emp.display();
}
return 0;
}
复制代码
3. 字符串流(String Stream)
字符串流用于处置惩罚内存中的字符串流。
#include <sstream>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Product {
string name;
double price;
int quantity;
void display() const {
cout << "Name: " << name << ", Price: " << price << ", Quantity: " << quantity << endl;
}
};
int main() {
vector<Product> products = {
{"Apple", 999.99, 5},
{"HuaWei", 699.99, 10},
{"SanXing", 299.99, 7}
};
ostringstream oss;
for (const Product& prod : products) {
oss << prod.name << " " << prod.price << " " << prod.quantity << "\n";
}
string productData = oss.str();
cout << "Serialized products:\n" << productData;
vector<Product> parsedProducts;
istringstream iss(productData);
string name;
double price;
int quantity;
while (iss >> name >> price >> quantity) {
parsedProducts.push_back({name, price, quantity});
}
cout << "Parsed products:" << endl;
for (const Product& prod : parsedProducts) {
prod.display();
}
return 0;
}
复制代码
4. 低级文件I/O(Low-level File I/O)
低级文件I/O使用系统调用来举行文件操作,提供了更高的灵活性和控制力。
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
struct Record {
char name[20];
int value;
void display() const {
cout << "Name: " << name << ", Value: " << value << endl;
}
};
int main() {
vector<Record> records = {
{"Record1", 100},
{"Record2", 200},
{"Record3", 300}
};
int fd = open("records.dat", O_WRONLY | O_CREAT, 0644);
if (fd == -1) {
cerr << "Error opening file for writing" << endl;
return 1;
}
for (const Record& rec : records) {
write(fd, &rec, sizeof(Record));
}
close(fd);
vector<Record> readRecords;
fd = open("records.dat", O_RDONLY);
if (fd == -1) {
cerr << "Error opening file for reading" << endl;
return 1;
}
Record rec;
while (read(fd, &rec, sizeof(Record)) > 0) {
readRecords.push_back(rec);
}
close(fd);
cout << "Read records:" << endl;
for (const Record& rec : readRecords) {
rec.display();
}
return 0;
}
复制代码
5. 内存映射文件(Memory-Mapped File I/O)
内存映射文件将文件内容映射到历程的地址空间。
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <cstring>
using namespace std;
struct Data {
char text[50];
int number;
void display() const {
cout << "Text: " << text << ", Number: " << number << endl;
}
};
int main() {
int fd = open("mmapdata.dat", O_RDWR | O_CREAT, 0644);
if (fd == -1) {
cerr << "Error opening file" << endl;
return 1;
}
Data data = {"Memory-mapped file example", 42};
write(fd, &data, sizeof(Data));
size_t filesize = sizeof(Data);
Data *map = static_cast<Data*>(mmap(0, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
if (map == MAP_FAILED) {
cerr << "Error mapping file" << endl;
close(fd);
return 1;
}
// 修改映射区域内容
strcpy(map->text, "Updated text");
map->number = 99;
// 取消映射
munmap(map, filesize);
close(fd);
// 读取文件内容
fd = open("mmapdata.dat", O_RDONLY);
if (fd == -1) {
cerr << "Error opening file" << endl;
return 1;
}
Data readData;
read(fd, &readData, sizeof(Data));
close(fd);
cout << "Read data:" << endl;
readData.display();
return 0;
}
复制代码
6. 网络I/O(Network I/O)
网络I/O用于通过网络举行数据传输,涉及到套接字编程。
服务器端
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
cerr << "Error creating socket" << endl;
return 1;
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(9090);
server_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
cerr << "Error binding socket" << endl;
close(server_fd);
return 1;
}
if (listen(server_fd, 5) == -1) {
cerr << "Error listening on socket" << endl;
close(server_fd);
return 1;
}
cout << "Server listening on port 9090..." << endl;
int client_fd = accept(server_fd, nullptr, nullptr);
if (client_fd == -1) {
cerr << "Error accepting connection" << endl;
close(server_fd);
return 1;
}
char buffer[256];
ssize_t bytesReceived = recv(client_fd, buffer, sizeof(buffer) - 1, 0);
if (bytesReceived == -1) {
cerr << "Error receiving data" << endl;
close(client_fd);
close(server_fd);
return 1;
}
buffer[bytesReceived] = '\0';
cout << "Received from client: " << buffer << endl;
const char *response = "Message received";
send(client_fd, response, strlen(response), 0);
close(client_fd);
close(server_fd);
return 0;
}
复制代码
客户端
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <iostream>
#include <cstring>
using namespace std;
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
cerr << "Error creating socket" << endl;
return 1;
}
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(9090);
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(sockfd, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
cerr << "Error connecting to server" << endl;
close(sockfd);
return 1;
}
const char *msg = "Hello, server!";
send(sockfd, msg, strlen(msg), 0);
char buffer[256];
ssize_t bytesReceived = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
if (bytesReceived == -1) {
cerr << "Error receiving data" << endl;
} else {
buffer[bytesReceived] = '\0';
cout << "Received from server: " << buffer << endl;
}
close(sockfd);
return 0;
}
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4