Show only some contents of a folder in a client/server in C

混江龙づ霸主 提交于 2019-12-12 04:54:45

问题


I'm developing a client/server program in C where I want to see the file contents in a folder. The program works, but I would to see only a .txt file, not all the files. How can I do this? Thank you!

DIR *dp;           
int rv,rv1,stop_received,nread2;       
struct dirent *ep;   
char buffer[300],appoggio[1000],buffer2[300];    
        dp = opendir ("./");
        if (dp != NULL){
            while (ep = readdir(dp)){
               if ((strcmp(ep->d_name, ".") == 0) 
|| (strcmp(ep->d_name,"..") == 0) 
|| (strcmp(ep->d_name, "SERVERD.c\0") == 0)
||(strcmp(ep->d_name, "h") == 0)
|| (strcmp(ep->d_name, "Menù segreteria") == 0)
||(strcmp(ep->d_name, "Menù docente") == 0)) 
continue;
           strcpy(buffer,ep->d_name);
           strcat(buffer,"\n");
           send(conn_fd, buffer,strlen(buffer), 0);   

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

回答1:


Just add another condition to the ones that call `continue:

|| ((4 <= strlen(ep->d_name)) && (strstr(ep->d_name, ".txt") == (ep->d_name + strlen(ep->d_name) - 4)))

Note: The 4 is derived from the number of characters in ".txt".

Note^2: The way the above test is coded if far from being efficient. Calling strlen() two time on the same "string" for example is not nice.



来源:https://stackoverflow.com/questions/28861544/show-only-some-contents-of-a-folder-in-a-client-server-in-c

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