Linux 实习日记:C 语言编写飞鸽传书 - 发送与接收文件功能
Linux 实习日记:C 语言编写飞鸽传书 - 发送与接收文件功能
日期:2021年10月15日 地点:公司办公室
今天我继续在 Linux 系统上开发飞鸽传书的功能。根据需求,我需要编写发送文件和接收文件的代码。
首先,我创建了一个名为send_file.c的文件来处理发送文件的功能。在这个文件中,我使用了 C 语言的文件操作函数来读取要发送的文件,并将其分片发送。我使用了套接字编程的send()函数来发送每个分片,确保文件可以完整地传输到接收端。我还使用了open()函数来打开要发送的文件,并使用read()函数来读取文件内容。
下面是我编写的发送文件代码的简要示例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#define CHUNK_SIZE 1024
int main() {
int sockfd; // 套接字描述符
FILE *file; // 文件指针
char buffer[CHUNK_SIZE]; // 缓冲区
ssize_t bytesRead; // 已读取的字节数
// 打开要发送的文件
file = fopen("file.txt", "rb");
if (file == NULL) {
perror("Error opening file");
return -1;
}
// 创建套接字并建立连接
// 发送文件内容
while ((bytesRead = fread(buffer, 1, CHUNK_SIZE, file)) > 0) {
if (send(sockfd, buffer, bytesRead, 0) == -1) {
perror("Error sending file");
return -1;
}
}
// 关闭文件和套接字
return 0;
}
然后,我创建了一个名为receive_file.c的文件来处理接收文件的功能。在这个文件中,我使用了 C 语言的文件操作函数来创建一个新文件,并使用套接字编程的recv()函数来接收发送端发送的文件分片。我使用了open()函数来创建新文件,使用write()函数来写入接收到的文件内容。
下面是我编写的接收文件代码的简要示例:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#define CHUNK_SIZE 1024
int main() {
int sockfd; // 套接字描述符
FILE *file; // 文件指针
char buffer[CHUNK_SIZE]; // 缓冲区
ssize_t bytesRead; // 已读取的字节数
// 创建新文件
// 接收文件内容
while ((bytesRead = recv(sockfd, buffer, CHUNK_SIZE, 0)) > 0) {
if (write(file, buffer, bytesRead) == -1) {
perror("Error writing to file");
return -1;
}
}
// 关闭文件和套接字
return 0;
}
在编写这两个功能的代码时,我还需要考虑错误处理和边界条件。例如,如果打开文件失败、发送/接收文件时发生错误,或者创建新文件失败,我都需要进行适当的错误处理。
明天,我将继续测试和完善这两个功能,以确保它们能够正确地发送和接收文件。
原文地址: https://www.cveoy.top/t/topic/p98N 著作权归作者所有。请勿转载和采集!