首页 > 解决方案 > 如何通过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;

标签: csocketssystem-calls

解决方案


推荐阅读