开发者

Get only the files included in a directory in c / Ubuntu

I have to create 开发者_StackOverflow社区a listing of the files contained inside a specific directory, I have done the code below(part of a bigger programm), but I would like my programm to ignore any possible folders that could be included inside the directory.

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>


int main ()
{
  DIR *dirptr;
  struct dirent *entry;     
  dirptr = opendir ("synchedFolder");



  if (dirptr != NULL)
  {
    while (entry = readdir (dirptr))
     {
         if(strcmp(entry->d_name,"..")!=0 && strcmp(entry->d_name,".")!=0)
          puts (entry->d_name);

     }

    (void) closedir (dirptr);
  }
  else
    perror ("ERROR opening directory");



}


If you want to list only files, but no directories, you have to add the following check:

entry->d_type == DT_REG

or

entry->d_type != DT_DIR


There's stat() and lstat() and the return value for stat. In the latter, look out for the S_ISDIR macro.


Short answer is the dirent structure includes the necessary information:

if ( entry->d_type == DT_REG)


Check stat (or lstat)

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>





/* int main (void){ */
int main (int argc, char **argv){
    int i,result=0;
    struct stat buf;

    /* print_S_I_types(); */


    for (i=1; i < argc; i++){
        if (lstat(argv[i], &buf) < 0) {
            fprintf(stderr, "something went wrong with %s, but will continue\n",
                   argv[i]);
            continue;
        } else {
            if S_ISREG(buf.st_mode){ 

                printf("argv[%d] is normal file\n",i);


            }else {
              printf("argv[%d] is not normal file\n",i);
            }
        }
    }

    return 0;
}


Working code for listing files (without directories):

#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>

int main()
{
    DIR *dir;
    struct dirent *ent;
    if ((dir = opendir ("/home/images")) != NULL) 
    {
        /* print all the files and directories within directory */
        while ((ent = readdir (dir)) != NULL) 
        {
            if(ent->d_type!= DT_DIR)
            {
                printf ("%s\n", ent->d_name);
            }
        }   
        closedir (dir);
    }
    else 
    {
        /* could not open directory */
        perror ("");
        return EXIT_FAILURE;
    }
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜