c - 打印文件传输额外的行

标签 c linux sockets

大家好,这是我上一个问题的延伸。这是链接

File Transfer application

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

ORBIT_SOCKETDIR=/tmp/orbit-cv

谁能告诉我发生了什么事。如何避免它存储在我的文件中

这是我的代码片段 客户端.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); 

服务器.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);

最佳答案

您正在尝试就地向 argv[3] 追加一个字符。但是,有 no guarantee已为其分配足够的内存以容纳额外的字符。

此外,一旦您用 \n 替换了 NUL 终止符,您就忘记了添加新的 NUL 终止符。

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

关于c - 打印文件传输额外的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9003904/

相关文章:

linux - 如何使用 "sed"在匹配/匹配后删除 2 行?

c - 系统调用进行中

node.js - 多个 Nodejs 服务器还是单个?

c# - 与经典 TCP 套接字通信

c - scanf 问题

c - 以编程方式获取直接连接设备的IP

c - 如何读取文件的第一个数字?

c++ - QGraphicsItem::toGraphicsObject() 在由 QGraphicsPixmapItem 派生的自己的类中返回 0

python - 防止第二个进程监听 Python 中的同一个管道

c - C 中的父/子 fork() 和管道