C - 将文件内容写入缓冲区
C - Write File Contents to a Buffer
我正在尝试打开一个文件然后将内容发送到 TCP 服务器。目前,我只是打开文件并将数据发送到缓冲区,服务器将访问该缓冲区。我不确定如何执行此操作以及如何跟踪单独文件中的所有位。我不是在寻找具体的答案,只要朝着正确的方向迈出一步就可以帮助解决问题!谢谢!
/* Open the input file to read */
FILE *fp;
fp = fopen(input_file, "r");
if (fp == NULL) {
perror("Error opening the file");
return(-1);
}
/* Send the contents of the input file to the server */
if (fgets(recvBuffer, buffer_size, fp)!=NULL) {
}
首先您需要在客户端和服务器之间设置网络基础设施(尝试查找有关如何在 C 中创建简单的客户端服务器应用程序的信息)。
然后就可以在客户端以二进制方式读取文件了。然后您可以决定是将整个文件发送到服务器,还是分块发送。
您需要考虑到 send/recv
等网络功能可能发送的字节数少于您告诉它们的字节数 - 因此您可能需要循环直到确保所有字节都已发送。
首先,您可以参考 here,它解决了我提到的所有要点。
使用您的代码的简单示例:
/* Open the input file to read */
FILE *fp;
fp = fopen(input_file, "r");
/*create address struct*/
struct sockaddr_in dest;
bzero(&dest,sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_addr.s_addr=inet_addr(/*addr*/); //ex "127.0.0.1"
dest.sin_port=htons(/*port*/); //ex 8888
if (fp == NULL) {
perror("Error opening the file");
return(-1);
}
int sock_fp = socket(AF_INET, SOCK_STREAM, 0); /*create socket with TCP transfer protocol*/
connect(sock_fp, (struct sockaddr *) &dest, sizeof(dest)); /*connect to server*/
/* Send the contents of the input file to the server */
while (fgets(recvBuffer, buffer_size, fp)!=NULL) {
sendto(sock_fp, recvBuffer, strlen(recvBuffer), 0, (struct sockaddr *)&dest, sizeof(dest));
}
close(sock_fp);
请注意,您需要在您提供的地址中有一台服务器侦听该端口。
另请注意,我将您的 if 更改为 while 循环,以防文件包含超过 1 行(fgets 逐行读取)
最后,如您所知,这包含最少的错误检查,我将执行检查以防 socket
无法创建套接字或 connect
失败。
我正在尝试打开一个文件然后将内容发送到 TCP 服务器。目前,我只是打开文件并将数据发送到缓冲区,服务器将访问该缓冲区。我不确定如何执行此操作以及如何跟踪单独文件中的所有位。我不是在寻找具体的答案,只要朝着正确的方向迈出一步就可以帮助解决问题!谢谢!
/* Open the input file to read */
FILE *fp;
fp = fopen(input_file, "r");
if (fp == NULL) {
perror("Error opening the file");
return(-1);
}
/* Send the contents of the input file to the server */
if (fgets(recvBuffer, buffer_size, fp)!=NULL) {
}
首先您需要在客户端和服务器之间设置网络基础设施(尝试查找有关如何在 C 中创建简单的客户端服务器应用程序的信息)。
然后就可以在客户端以二进制方式读取文件了。然后您可以决定是将整个文件发送到服务器,还是分块发送。
您需要考虑到 send/recv
等网络功能可能发送的字节数少于您告诉它们的字节数 - 因此您可能需要循环直到确保所有字节都已发送。
首先,您可以参考 here,它解决了我提到的所有要点。
使用您的代码的简单示例:
/* Open the input file to read */
FILE *fp;
fp = fopen(input_file, "r");
/*create address struct*/
struct sockaddr_in dest;
bzero(&dest,sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_addr.s_addr=inet_addr(/*addr*/); //ex "127.0.0.1"
dest.sin_port=htons(/*port*/); //ex 8888
if (fp == NULL) {
perror("Error opening the file");
return(-1);
}
int sock_fp = socket(AF_INET, SOCK_STREAM, 0); /*create socket with TCP transfer protocol*/
connect(sock_fp, (struct sockaddr *) &dest, sizeof(dest)); /*connect to server*/
/* Send the contents of the input file to the server */
while (fgets(recvBuffer, buffer_size, fp)!=NULL) {
sendto(sock_fp, recvBuffer, strlen(recvBuffer), 0, (struct sockaddr *)&dest, sizeof(dest));
}
close(sock_fp);
请注意,您需要在您提供的地址中有一台服务器侦听该端口。
另请注意,我将您的 if 更改为 while 循环,以防文件包含超过 1 行(fgets 逐行读取)
最后,如您所知,这包含最少的错误检查,我将执行检查以防 socket
无法创建套接字或 connect
失败。