IO进程 day3 C语言

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

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

#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 <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值