linux C服务器客户端流文件

时间:2012-09-20 04:27:41

标签: c linux

我正在尝试将文件从客户端流式传输到服务器,但是从FILE到char存在不兼容的数据类型,因此每次运行客户端时都会出现分段错误。我不知道怎么解决这个问题。附件是服务器和客户端的代码,以及客户端的问题。我试图从客户端读取文件缓冲区将其发送到服务器,服务器将从缓冲区读取文件并将其写入文件。 客户端http://pastebin.com/QtLbMgP3

服务器端http://pastebin.com/8PNchBUZ

// n = write(sock,"send me your message",18);
    printf("Please enter the message: ");
    bzero(buffer,256);
    fgets(buffer,255,stdin);
        ptr_myfile=fopen("test2.txt","w");

         for(counter=1;counter <=10;counter++){
             fwrite(&ptr_myfile,sizeof(*buffer),1,buffer);
             n = read(sockfd,buffer,255);
             n = write(sockfd,buffer,18);

             n = write(sockfd,buffer,strlen(buffer));
             if (n < 0) error("ERROR writing to socket");
             bzero(buffer,256);
             n = read(sockfd,buffer,255);
             if (n < 0) error("ERROR reading from socket");
             // printf("%s\n",buffer);
         };//close for loop
    close(sockfd);

    }// close event loop
    return 0;
}// close main function

3 个答案:

答案 0 :(得分:1)

在不通过所有代码的情况下,readwriteclose系列API(非fopenfread等)都有一个整数描述符,而不是FILE*

您不能将FILE*int混在一起。

答案 1 :(得分:1)

在这里看这一行:

fwrite(&ptr_myfile,sizeof(*buffer),1,buffer);

如何编译?

这可能是正确的:

fwrite(buffer, 1, sizeof(buffer), ptr_myfile );

上面一行将从文件读取最多 256字节(缓冲区数组的大小),并将数据复制到 buffer 。请注意,我正在传递ptr_myfile,而不是&amp; ptr_myfile。

答案 2 :(得分:1)

检查你的fwrite语句,你试图写入文件,还是从文件读入缓冲区?

如果是前一种情况,则使用fwrite(buffer,sizeof(buffer),1,ptr_myfile),即您要写入的流是最后一个变量。

如果案例是后者,那么在实际将其放入缓冲区之前,首先需要使用fgets或getchar或类似函数从流中读取。

希望它有所帮助!


好的,要在客户端读取文件并将其发送到服务器,

fp=fopen("<filename>", "r");
//This opens the file and initializes the pointer fp to the start of the file Start of
//the file, not its text necessarily

现在你可以使用fgetc()函数[逐个字符]或fgets()函数[如果格式化了文本,你可以将整行读入缓冲区]从文件中读取到缓冲区。

fgets(buffer,sizeof(buffer),fp);
//This could be ambiguous as the second argument should correspond to
//pre-known limit of bytes to read here some Macro maybe.

现在,简单地使用send()将此缓冲区分派给服务器。

在服务器端,使用recv()从网络接收输入数据到某个'缓冲区',并使用fputs或fprintf或任何方便的函数写入以写模式打开的文件。

相关问题