c++实现文件传输代码
时间: 2025-01-07 22:10:54 浏览: 12
在C++中实现文件传输通常涉及到网络编程,特别是通过socket通信来发送和接收文件。这里是一个简单的例子,展示了如何使用`std::ifstream`读取本地文件,并使用`std::ofstream`写入到另一台远程主机上:
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <sys/socket.h> // 对于socket操作
#include <arpa/inet.h> // 对于inet_addr等网络函数
// 创建套接字并设置为TCP/IP
int create_socket() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
std::cerr << "Error creating socket" << std::endl;
return -1;
}
return sock;
}
// 连接到服务器
bool connect_to_server(int sock, const char* server_ip, int port) {
struct sockaddr_in server_address;
bzero(&server_address, sizeof(server_address));
server_address.sin_family = AF_INET;
inet_aton(server_ip, &server_address.sin_addr);
server_address.sin_port = htons(port);
if (connect(sock, (struct sockaddr*)&server_address, sizeof(server_address)) == -1) {
perror("Error connecting to server");
close(sock);
return false;
}
return true;
}
// 发送文件
void send_file(const std::string& filename, int sock) {
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()) {
std::cerr << "Failed to open file " << filename << std::endl;
return;
}
std::string buffer((std::istreambuf_iterator<char>(file)), {});
file.close();
std::cout << "Sending file..." << std::endl;
send(sock, buffer.c_str(), buffer.size(), 0);
}
// 接收文件
void receive_file(int sock, std::string& output_filename) {
char received_buffer[4096];
size_t bytes_received;
std::ofstream output(output_filename, std::ios::binary | std::ios::trunc);
if (!output.is_open()) {
std::cerr << "Failed to open output file" << std::endl;
return;
}
while ((bytes_received = recv(sock, received_buffer, sizeof(received_buffer), 0)) > 0) {
output.write(received_buffer, bytes_received);
}
output.close();
if (bytes_received == 0) {
std::cerr << "Server closed connection." << std::endl;
} else if (bytes_received == -1) {
perror("Error receiving file");
}
}
int main() {
int sock = create_socket();
if (sock < 0) {
return 1;
}
// 设置服务器地址和端口
char server_ip[] = "your_server_ip";
int port = your_server_port;
if (!connect_to_server(sock, server_ip, port)) {
return 1;
}
std::string input_filename = "path_to_your_input_file";
std::string output_filename = "output_file_name";
send_file(input_filename, sock); // 发送文件
receive_file(sock, output_filename); // 接收文件
close(sock);
return 0;
}
```
注意这只是一个基础示例,实际应用中还需要处理错误、异常以及连接关闭等情况。此外,为了安全性和效率,最好使用SSL/TLS进行加密通信。
阅读全文