[Linux C] recursively iterates through subdirectories and files in the specified directory __linux

Source: Internet
Author: User
/*
	function: Demonstrates the use of the C language recursively to traverse the subdirectory under the specified directory (excluding hidden directories) and file
* * *
#include <stdio.h>
#include <dirent.h >
#include <string.h>

void List (char *path)
{
	struct dirent *ent = NULL;
	DIR *pdir;
	if ((Pdir = opendir (path))!= null)
	{while
		(null!= (ent = Readdir (pdir)))
		{
			if (Ent->d_type = 8) c14/>//d_type:8-file, 4-Directory
				printf ("file:\t%s\n", ent->d_name);
			else if (ent->d_name[0]!= '. ')
			{
				printf ("\n[dir]:\t%s\n", ent->d_name);
				List (ent->d_name);					Recursively traverse subdirectory
				printf ("Return [%s]\n\n", ent->d_name);
			}
		Closedir (Pdir);
	}
	else
		printf ("Open dir-[%s] failed.\n", path);
}

int main () 
{         
	char path[] = "/home/zcm/program/test";
	List (path);

	return 0; 
}



Program Run Result:

File:	travel.c
file:	p1.c
file:	20111012.log

[Dir]:	test
file:	temp.txt
file:	b.c
file:	convert2.sh
file:	d.txt	file: A.C file: D.C
file:	convert1.sh
file:	tst.c
file:	test.sh
return [test]


[Dir]:	Whatdir
file:	a1.c
file:	a2.c
return [whatdir]

file:	p1
file:	Travel
file:	a.sh
file:	20111005.log	travel.cpp
file: P0 file:	Wht.log
File: 2011ty12.log: P2 file: 20111120.log file:	p2.c	file Whatarey.log
file:	20011008.log
file:	20111006.log
file:	p0.c

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.