clear
clear----clear the terminal screen 清空终端屏幕
#include<stdio.h>
int main()
{
fputs("\x1b[2J\x1b[H",stdout);
return 0;
}
解析
简单两行代码就实现了清屏功能,那么稀奇古怪的字符都代表了什么呢?
其实这些都是VT100里面的控制码,所谓VT100,是一个终端类型的定义
“\x1b[2J” 清楚整个屏幕,行属性变成单宽单高,光标位置不变
“\x1b[H” 光标移动
\033[1m 设置为高亮
\033[30m - \033[37m 设置前景色
30:黑色 31:红色 32:绿色 33:黄色
34:蓝色 35:紫色 37:白色
\033[40m - \033[47m 设置背景色
40: 黑色 41:红色 42:绿色 43:黄色
44:蓝色 45:紫色 46:青色 47:白色
pwd
pwd----print name of current/working directory//打印当前目录及路径名
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
char buff[256]={0};
getcwd(buff,256);
printf("%s\n",buff);
exit(0);
}
解析
通过getcwd函数实现
getcwd----get current working directory//获得当前目录位置
getcwd(char* buff,size_t size);//将当前位置存在buff中
ls
ls----list directory contents 列出目录内容
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
#include<unistd.h>
#include<sys/stat.h>
#include<dirent.h>
int main()
{
char buff[256]={0};
getcwd(buff,256);
DIR* p=opendir(buff);
if(p==NULL)
{
perror("open failed");
exit(0);
}
struct dirent* s=NULL;
struct stat st;
while((s=readdir(p))!=NULL)
{
if(strncmp(s->d_name,".",1)==0)
{
continue;
}
lstat(s->d_name,&st);
if(S_ISDIR(st.st_mode))
{
printf("\033[1;34m%s\033[0m ",s->d_name);
}
else
{
if(st.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH))
{
printf("\033[0;32m%s\033[0m ",s->d_name);
}
else
{
printf("%s ",s->d_name);
}
}
}
printf("\n");
closedir(p);
exit(0);
}
解析:
-
首先是通过getcwd获得当前位置即当前目录
#include<unistd.h> getcwd(buff,256);
-
然后通过opendir 打开一个目录
#include<sys/types.h> #include<dirent.h> DIR* p=opendir(buff);
函数原型是:DIR* opendir (const char * path );
如果path是目录就会成功获取,如果是文件就返回NULL;
返回值类型:DIR* // DIR是一个结构体 原型为struct_dirstreamtypedef struct __dirstream DIR; struct __dirstream { void *__fd; /* `struct hurd_fd' pointer for descriptor. *///结构赫德fd的指针描述符 char *__data; /* Directory block. *///目录块 int __entry_data; /* Entry number `__data' corresponds to. */目录块对应的编号 char *__ptr; /* Current pointer into the block. */当前指向目录块的指针 int __entry_ptr; /* Entry number `__ptr' corresponds to. */指向目录块的指针的编号 size_t __allocation; /* Space allocated for the block. */为块分配的空间 size_t __size; /* Total valid data in the block. */块中有效数据的个数 __libc_lock_define (, __lock) /* Mutex lock for this structure. */这个结构的互斥锁 };
-
然后读取opendir中返回的列表 DIR结构体
#include<dirent.h> struct dirent* s=NULL; while((s=readdir(p))!=NULL) {}
返回值:返回dirent的结构体指针
struct dirent { long d_ino; /* inode number 索引节点号 */ off_t d_off; /* offset to this dirent 在目录文件中的偏