c - 如何通过c中的套接字读取文件并写入另一个文件
问题描述
我尝试在客户端读取文件,在套接字上写入,然后在服务器端取回数据并将其写入另一个文件,但它不起作用。我是 c 和系统调用的新手。
这是我的代码。
客户端:
struct stat file_stat;
FILE *file;
//Make connection to server
void connect_to(char* localhost, int port){
int socketfd = ssocket();
printf("[+]Server socket created successfully.\n");
sconnect(localhost, port, socketfd);
printf("[+]Connected to Server.\n");
file = fopen("tosend.txt", "r"); //open file
//GET FILE SIZE
//fstat(fdfile, &file_stat);
//printf("File Size: \n%ld bytes\n", file_stat.st_size);
char data[BUFFER_SIZE] = {0};
while (fgets(data, BUFFER_SIZE, file) != NULL)
{
for (int i = 0; i < BUFFER_SIZE; i++)
{
swrite(socketfd, &data, BUFFER_SIZE);
}
}
printf("[+]File data sent successfully.\n");
sclose(socketfd);
}
服务器端:
//while (1)
//{
newsockfd = accept(sockfd,NULL,NULL);
//INIT
FILE *fp;
char *filename = "tosend2.c";
char buffer[BUFFER_SIZE];
//write file
fp = fopen(filename, "w");
read(newsockfd, &buffer, BUFFER_SIZE);
write(1, buffer, BUFFER_SIZE);
fprintf(fp, "%s\n", buffer);
bzero(buffer, BUFFER_SIZE);
close(newsockfd);
close(sockfd);
return 0;
解决方案
推荐阅读
- c++ - 它->首先给出什么类型?
- sql - 如何将 Array[String] 输出到 Json 文件?
- ios - Xcode 非公共 API
- angular - 更新 Angular 8.0 后模块没有导出的成员组件
- django - Django Cassandra 引擎没有正确记录日期时间
- php - laravel nova 隐藏索引页面上的编辑按钮
- r - 向量长度不均匀的expand.grid问题
- laravel - 默认 laravel 通知 --> 数据不工作
- c# - .NET Core JsonDocument.Parse(ReadOnlyMemory
, JsonReaderOptions) 无法从 WebSocket ReceiveAsync 解析 - javascript - 如何检查图像的 src 属性是否有效?