IO进程 day3 C语言

1. 打印指定目录下的所有文件名,除了隐藏文件,输入编号,可以将编号对应的文件内容显示在终端上。

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define MAXSIZE 128

char *get_filename(char *s){
	DIR *dir = opendir(s);
	if(dir == NULL){
		return NULL;
	}
	struct dirent *rp[MAXSIZE];
	int count = 1;
	while(rp[count - 1] = readdir(dir)){
		if(rp[count -1]->d_name[0] != '.'){
			printf("[%02d] %s\n",count,rp[count -1]->d_name);
			count++;
		}
	}
	if(count == 1){
		printf("The directory %s is empty.\n",s);
		return NULL;
	}

	int file_num = 0;
	printf("PLease enter the number of the file to open:\n");
	scanf("%d",&file_num);
	if(rp[file_num - 1]->d_type == DT_DIR){
		printf("%s is a directory\n",rp[file_num -1]->d_name);
		strcat(s,rp[file_num - 1]->d_name);
		strcat(s,"/");
		get_filename(s);
	}else{
		strcat(s,rp[file_num - 1]->d_name);
	}
	closedir(dir);
	dir = NULL;
	return s;
}
void reveal_content(char *s){
	int fd = open(s,O_RDONLY);
	if (fd < 0){
		perror("open");
		return;
	}
	char str[20] = "";
	while(1){
		bzero(str,sizeof(str));
		ssize_t res = read(fd,str,sizeof(str)-1);
		if(res == 0){
			break;
		}
		printf("%s",str);
	}
	puts("");
	if (close(fd) < 0){
		perror("close");
		return;
	}
}

int main(int argc, const char *argv[])
{
	char my_path[MAXSIZE] = "./";
	strcpy(my_path,get_filename(my_path));
	reveal_content(my_path);
	return 0;
}

2. 显示指定路径下所有文件的权限 硬链接数 时间 以及名字

#include 
#include 
#include 
#include 
#include 
#include 

void my_ls(char *s){
	DIR *dir = opendir(s);
	if(dir == NULL){
		perror("opendir");
		return;
	}
	struct dirent *rd = NULL;
	struct stat st;

	while(rd = readdir(dir)){
		char file_path[128] = "";
		strcat(file_path,s);
		printf("%-30s",rd->d_name);
		strcat(file_path,rd->d_name);
		int status = stat(file_path,&st);
		if(status < 0){
			perror("stat");
			return;
		}
		printf("%10d\t",st.st_mode);
		printf("%5ld\t",st.st_nlink);
		printf("%15ld\t",st.st_ctime);
		puts("");
	}
	closedir(dir);
	dir = NULL;
}
int main(int argc, const char *argv[])
{
	char path[128] = "";
	printf("Please enter the directory path:\n");
	scanf("%s",path);
	my_ls(path);
	return 0;
}

你可能感兴趣的:(c语言,c++,算法)