Linux系統——rm命令的代碼實現

實現Linux系統下rm -rf xxx刪除非空目錄的功能

#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>

void del_stat(const char* name)
{
	DIR* fl = opendir(name);
	chdir(name);
	
	for(struct dirent* dir = readdir(fl); NULL!=dir;)
	{
		if(dir->d_type == DT_DIR)
		{
			if(strcmp(dir->d_name,"..")&&strcmp(dir->d_name,"."))
				del_stat(dir->d_name);
		}
		remove(dir->d_name);
		dir = readdir(fl);
	}
	chdir("..");
	remove(name);
}

int main(int argc,char *argv[])
{
	if(3 != argc)
	{
		printf("User:./rm -rf xxx\n");
		return -1;
	}
	
	struct stat sta;
	if(0 > stat(argv[2],&sta))
	{
		perror("open");
		return -1;
	}

	if(!S_ISDIR(sta.st_mode))
	{
		char temp;
		printf("該文件是一個文件,是否刪除(y)、(n):");
		scanf("%c",&temp);
		if(temp == 'n')return 0;
		remove(argv[2]);
		return 0;
	}
	
	del_stat(argv[2]);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章