Linux命令
配套视频https://www.bilibili.com/video/BV1dt411f7TZ?p=87
p87 - p98
Day5 笔记
1. linux文件操作相关函数
stat函数
穿透函数 --软链接
stat 文件名 显示文件属性信息 == ls -l 文件名
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("./a.out filename\n");
exit(1);
}
// argv[0] = ./a.out
struct stat st;
int ret = stat(argv[1], &st);
//若更换为lstat 则软链接不穿透
if (ret == -1)
{
perror("stat");
exit(1);
}
//获取文件大小
int size = (int)st.st_size;
printf("file size = %d\n", size);
}
lstat函数
不穿透,直接读软链接的大小
其他不穿透命令有 ls-l rm
access函数
测试文件是否有某种权限
返回值 成功为0 失败为-1
chmod函数
改变文件的权限
chmod(argv[1], 0755)
chown(argv[1], 116, 115)
truncate函数
文件拓展
文件长度 若指定长度小于文件长度 则文件截取
若指定长度大于文件长度,则文件拓展
链接函数
link函数
创建硬链接 int link(const char* oldpath, const char* newpath);
symlink函数
创建软链接
readlink函数
读软链接 读取路径
unlink函数
删除文件 制作临时文件
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int main(int argc, char *argv[])
{
int fd = open("filename", O_CREAT | O_RDWR, 0664);
if (fd == -1)
{
perror("open");
exit(1);
}
//删除临时文件
int ret = unlink("timefile");
//写文件
write(fd, "hello\n", 6);
//读文件
lseek(fd, 0, SEEK_SET); // 重置文件指针
char buf[24] = { 0 };
int len = read(fd, buf, sizeof(buf));
//读出的内容,写到屏幕上
write(1, buf, len);
close(fd);
return 0;
}
rename函数
man 2 rename
2. linux目录相关操作函数
chdir函数 修改当前进程路径 0成功 -1 失败
getcwd函数 获取当前程序路径
mkdir函数 创建目录 需要有权限
rmdir函数 删除空目录
opendir 打开目录
readdir 读目录
#include<stdlib.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<dirent.h>
int getFileName(char* root)
{
//open file
DIR * dir = NULL;
dir = opendir(root);
if (dir == NULL)
{
perror("open file");
exit(1);
}
// 遍历当前目录
struct dirent* ptr = NULL;
char path[1024] = { 0 };
int total = 0;
while (ptr = readdir(dir) != NULL)
{
//过滤 . 和..
if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0)
{
continue;
}
//遇到目录
if (ptr->d_type == DT_DIR)
{
//递归读取目录
sprintf(path, "%s/%s", root, ptr->d_name);
total += getFileName(path);
}
//普通文件
if (ptr->d_type == DT_REG)
{
total++;
}
}
closedir(dir);
return total;
}
int main(int argc, char *argv[])
{
//获取指定文件目录下的 所有文件
if(argc < 2)
{
printf("./a.out dir\n");
exit(1);
}
int total = getFileName(argv[1]);
printf("%s has file numbers %d\n", argv[1],total);
return 0;
}
3. fcntl函数
改变已经打开的文件的属性
打开文件的时候属性为只读 要修改为O_APPEND
-
复制现有描述符
-
获得文件描述符标记
-
获得设置文件状态标记 int fd, int cmd, long arg;
F_GETFL F_SETFL可以修改 O_APPEND(追加写) O_NONBLOCK(设置为非阻塞) -
获得异步io所有权
-
获得记录锁
flag = fcntl(fd, F_GETFL, 0); //获取文件状态 flag |= O_APPEND; //追加写 则不会覆盖原来的内容 fcntl(fd, F_SETFL,flag);
4. dup、dup2函数
复制现有文件描述符
dup返回的是文件描述表中没有被占用的最小的文件描述符
dup2 把old复制给new
dup2(old, new)
如果new是一个已经被打开的文件描述符,在拷贝前先关掉new;
如果old和new是同一个描述符则直接返回文件描述符,不会关闭old