打印文件传输额外行

时间:2012-01-25 13:58:53

标签: c linux sockets

大家好,这是我之前提问的扩展名。这是链接

File Transfer application

我在文件名末尾插入了一个'/ n',并成功检索文件名和文件中的数据。但是有一些问题,在我的服务器端从套接字读取字节到'/ n'之后,它还在我的文件的开头写了一个奇怪的语句

ORBIT_SOCKETDIR = / TMP /轨道-CV

任何人都可以告诉我发生了什么。如何避免它存储在我的文件中

这是我的代码片段 client.c

 char * filename = strrchr(argv[3],'/'); // extracting file name from path
    *filename++; filename[strlen(filename)] = '\n'; // putting /n at the end of file name n = write(sockfd, filename, strlen(filename));
    bzero(buffer,256); FILE *f = fopen("file.txt" ,"rb");  // opening the file 
    size_t bytes = 0; 

    // sending the actual data in the file
    while((bytes = fread(buffer ,sizeof(char) ,sizeof(buffer) ,f))>0) 
       send(sockfd ,buffer ,bytes , 0); 

server.c

 while(ch[0] != '\n')    // here reading the filename
{
    n = read(newsockfd,ch,1);
    filename[i] = ch[0];
    printf("ch %c " , ch[0]);
     i++;
}


 FILE *f = fopen(filename ,"wb");

// reading the actual data and writing it in the file 
while((bytes = recv(newsockfd ,buffer , sizeof(buffer) ,0))>0)
   fwrite(buffer,sizeof(char) ,bytes , f);

1 个答案:

答案 0 :(得分:2)

您正尝试将字符附加到argv[3]就地。但是,no guarantee已经为它分配了足够的内存以容纳额外的字符。

此外,在您使用NUL替换\n终结符后,您将忘记添加新的NUL终止符。

总结:为argv[3]加上\n加上NUL分配足够的内存,将字符串复制到其中,最后附加\nNUL

相关问题