linux下利用系统函数实现rm -rf的功能!

刚学习linux下的文件和目录函数,利用这些写个linux的rm -rf功能模块。希望大家多多点评!!!


#include
#include
#include
#include
void removedir(char* dir);
void removefile(char *name)//remove file and empty dir
{
	DIR *d;
	if ((d = opendir(name)) == NULL)
	{
		printf("file:%s is moved!\n", name);
		unlink(name);
	}
	else if ((rmdir(name)) == 0)
			printf("dir:%s is moved!\n", name);
	else
		{
			printf("dir name:%s\n", name);
			removedir(name);
		}
}

void removedir(char* dir)//check the dir
{
	struct dirent *dp;
	DIR *d;
	char bb[100] = "";
	d = opendir(dir);
	getcwd(bb, 100);
	while((dp = readdir(d)) != NULL)
	{
		if (strcmp(dp->d_name, ".") == 0 || strcmp(dp->d_name, "..") == 0)
			continue;
		chdir(dir);
		printf("\nfind :%s\n", dp->d_name);
		removefile(dp->d_name);
	}
	closedir(d);
	chdir(bb);
	removefile(dir);
	printf("%s is moved!\n", dir);
}

int main(int argc, char* argv[])
{
	if (argc < 2)
	{
		printf("./app file or dir!\n");
		exit(1);
	}
	removefile(argv[1]);
	printf("remove successful\n!");
	return 0;
}

你可能感兴趣的:(linux)