【问题标题】:How to insert a newline in a recv in C如何在C中的recv中插入换行符
【发布时间】:2015-02-27 18:59:46
【问题描述】:

我编写此代码是为了从服务器发送文件夹中的文件内容列表,以便在客户端中查看。该代码有效,但我看到所有文件都没有换行符。如何查看带有换行符或空格的文件? 例如,现在我看到:“file1.txtfile2.txtfile3.txt”,我会看到“file1.txt 文件 2.txt 文件 3.txt"

谢谢!

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);

【问题讨论】:

    标签: c sockets client


    【解决方案1】:

    简单,像这样声明一个换行符

    char newline = '\n';
    

    然后发送

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

    所以如果你想在它之后发送目录名和换行符,这样做

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

    【讨论】:

    • 您可能想告诉该人何时/何处发送它?
    • 并且可能最好建议发送一个 CR/LF ("\r\n"),这或多或少是网络应用程序的标准。
    • 它不起作用。对于编译器,错误是“size_t length;”在此期间。
    • @Heisenberg 包含stdlib.h 或将size_t 更改为unsigned int
    • 对不起,它在列表的末尾或开头也显示一些点是否正常?
    猜你喜欢
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 2018-04-23
    • 2019-05-27
    • 1970-01-01
    • 2012-04-16
    相关资源
    最近更新 更多