问题
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