Linux C Read the file name of all files (including subfolders) under the folder (GO)

Source: Internet
Author: User
Tags strcmp

Linux C reads the folder below to use the struct struct dirent, in header # include <dirent.h>, as follows:

1#include <dirent.h>2 structdirent3 {4    LongD_ino;/*inode Number Index node*/5off_t D_off;/*offset to this dirent in the directory file*/6Unsigned ShortD_reclen;/*length of this d_name filename long*/7UnsignedCharD_type;/*The type of d_name file type*/8    CharD_name [name_max+1];/*File name (null-terminated) file name, maximum 255 characters*/9}

Where D_type indicates the type of file: File (8), directory (4), linked file (10), and so on.

The following program recursively reads all filenames under a folder and its subfolders:

#include <stdio.h>#include<stdlib.h>#include<string.h>#include<dirent.h>#include<unistd.h>intReadFileList (Char*basepath) {DIR*dir; structDirent *ptr; Char Base[ +]; if((Dir=opendir (basepath)) = =NULL) {Perror ("Open dir error ..."); Exit (1); }     while((Ptr=readdir (dir))! =NULL) {        if(strcmp (Ptr->d_name,".")==0|| strcmp (Ptr->d_name,"..")==0)///Current dir OR parrent dir            Continue; Else if(Ptr->d_type = =8)///fileprintf"d_name:%s/%s\n",basepath,ptr->d_name); Else if(Ptr->d_type = =Ten)///Link Fileprintf"d_name:%s/%s\n",basepath,ptr->d_name); Else if(Ptr->d_type = =4)///dir{memset (Base,' /',sizeof(Base)); strcpy (Base, BasePath); strcat (Base,"/"); strcat (Base,ptr->d_name); ReadFileList (Base);    }} closedir (dir); return 1;}intMainvoid) {DIR*dir; Charbasepath[ +]; //get the current absoulte pathmemset (BasePath,' /',sizeof(BasePath)); GETCWD (BasePath,999); printf ("The current dir is:%s\n", BasePath); //get the file list//memset (BasePath, ' n ', sizeof (BasePath)); //strcpy (BasePath, "./xl");readfilelist (BasePath); return 0;}

Execution output:

Linux C Read the file name of all files (including subfolders) under the folder (GO)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.