How to insert a newline in a recv in C

倖福魔咒の 提交于 2019-12-11 16:46:28

问题


I write this code to send the list of files contents in a folder from a server for see it in a client. The code works, but I see all files without a newline. How can I see the files with a newline or space? For example, now I see: "file1.txtfile2.txtfile3.txt" and I would see "file1.txt file2.txt file3.txt"

Thank you!

DIR *dp;           
int rv, stop_received;       
struct dirent *ep;           

dp = opendir ("./");
char *newline="\n";  
if (dp != NULL) {
    while (ep = readdir(dp))                      
        rv = send(conn_fd, ep->d_name, strlen(ep->d_name), 0);               

    (void)closedir(dp);
} else
    perror ("Couldn't open the directory");           
close(conn_fd);

回答1:


Easy, declare a newline like this

char newline = '\n';

and send it

rv = send(conn_fd, &newline, 1, 0);

So if you want to send the directory name and a newline after it, do it this way

char newline;

newline = '\n';
while (ep = readdir(dp))
{
    size_t length;

    length = strlen(ep->d_name);
    rv     = send(conn_fd, ep->d_name, length, 0); 
    if (rv != length)
        pleaseDoSomething_ThereWasAProblem();
    rv = send(conn_fd, &newline, 1, 0);
   /* ... continue here ... */
}


来源:https://stackoverflow.com/questions/28772357/how-to-insert-a-newline-in-a-recv-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!