作业:
1. 打印指定目录下的所有文件名,除了隐藏文件,输入编号,可以将编号对应的文件内容显示在终端上。
ubuntu@ubuntu:~/32/work/hoilday$ cat 1.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<dirent.h>
#include<errno.h>
#define MAXSIZE 200
//结构体定义
typedef struct Node
{
union
{
int len;
char str[MAXSIZE];
};
struct Node *next;
}*linklist;
//单向链表结点的创建
linklist create(int flag)
{
linklist L=(linklist)malloc(sizeof(struct Node));
if(NULL==L)
return NULL;
if(flag==1)
L->len=0;
if(flag==0)
strcpy(L->str,"");
L->next=NULL;
return L;
}
//尾插
int insert_rear(linklist L,char* str)
{
//1,判断链表是否创建成功
if(L==NULL)
{
return -1;
}
//2,插入的值
linklist p=L;
while(p->next!=NULL)
{
p=p->next;
}
//3,在p节点的后面插入新节点s
linklist s=create(0);
if(s==NULL)
{
return -1;
}
strcpy(s->str,str);
p->next=s;
L->len++;
}//单向链表尾删
int delete_rear(linklist L)
{
if(L==NULL||L->next==NULL)
return -1;
linklist p=L;
while(p->next->next!=NULL)
p=p->next;
linklist q=p->next;
p->next=q->next;
free(q);
q=NULL;
L->len--;
}
//单向链表空间释放
linklist free_space(linklist L)
{
if(NULL==L)
return NULL;
int n=L->len;
for(int i=0;i<n;i++)
{
delete_rear(L);
}
free(L);
L=NULL;
return L;
}
//按下标查找
char* search_pos(linklist L,int pos)
{
//1,判断链表是否创建成功
//2,判断链表是否为空
//3,判断位置是否合法
if(L==NULL ||L->next==NULL || pos<1|| pos>L->len)
{
return NULL;
}
//4,循环到pos起名字p
linklist p=L;
for(int i=0;i<pos;i++)
{
p=p->next;
}
//5,查找:输出
return p->str;
}
int main(int argc, const char *argv[])
{
linklist L=create(1);
DIR *dp = opendir("/home/ubuntu/32/work/hoilday/");
if(NULL==dp)
{
perror("opendir");
return -1;
}
printf("opendir success\n");
int count = 1;
struct dirent* rp = NULL;
while(1)
{
rp = readdir(dp);
if(NULL==rp)
{
if(0==errno)
{
printf("读取完毕\n");
break;
}
else
{
perror("readdir");
return -1;
}
}
if(rp->d_name[0]!='.')
{
printf("[%d]%s\n",count++,rp->d_name);
insert_rear(L,rp->d_name);
}
}
int num;
char arr[MAXSIZE]="";
printf("请输入要查看的目录编号:");
scanf("%d",&num);
int res = open(search_pos(L,num),O_RDWR);
if(res==-1)
{
perror("open");
return -1;
}
while(1)
{
ssize_t t = read(res,arr,sizeof(arr)-1);
if(t==0)
break;
write(1,arr,t);
}
closedir(dp);
return 0;
}
2. 显示指定路径下所有文件的权限 硬链接数 时间 以及名字
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int main(int argc, const char *argv[])
{
struct stat buf;
if(stat("./01_fopen.c",&buf)<0)
{
perror("stat");
return -1;
}
printf("mode:%o\n",buf.st_mode);
printf("link:%ld\n",buf.st_nlink);
printf("uid:%d gid:%d\n",buf.st_uid,buf.st_gid);
printf("size:%ld\n",buf.st_size);
printf("time:%ld\n",buf.st_ctime);
return 0;
}