How to insert a newline in a recv in C

2019-09-04 06:40发布

问题:

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 ... */
}


标签: c sockets client