一、 access
access
是一个系统调用函数,用于检查文件或目录的访问权限。它允许程序在尝试执行某个操作之前,预先检查文件或目录是否存在以及是否具有所需的权限。
//
// Created by zhangchuang on 2023/9/20.
//
/*
#include <unistd.h>
int access(const char *pathname, int mode);
作用:
判断某个文件是否有某个权限,或者判断文件是否存在
参数:
-pathname:
判断文件路径
-mode:
R_OK:判断是否有读权限
W_OK:判断是否有写权限
X_OK:判断是否有执行权限
F_OK:判断文件是否存在
返回值:
成功:
0
失败:
-1
*/
#include <unistd.h>
#include <stdio.h>
int main(){
int ret = access("F:\\C++\\C++\\c++linux\\linux_io_fun\\cpy.txt",F_OK);
if(ret==-1){
perror("access");
}
printf("文件在");
return 0;
}
二、chmod
chmod
是一个系统调用函数,用于更改文件的权限位。它允许程序员在运行时修改文件的读取、写入和执行权限
//
// Created by zhangchuang on 2023/9/20.
//
/*
#include <sys/stat.h>
int chmod(const char *pathname, mode_t mode);
修改文件的权限
参数:
-Pathname: 需要修改的文件路径
-mode: 需要修改的权限值,八进制数
*/
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
int main(){
int ret = chmod("a.txt",0775);
if(ret==-1){
perror("chmod");
}
printf("文件修改成功");
return 0;
}
三、chown
chown
是一个系统调用函数,用于更改文件或目录的所有者和组。它通常在UNIX和类UNIX操作系统中使用。通常,只有超级用户(root)才能更改文件或目录的所有者和组。普通用户可以更改自己拥有的文件的组,但不能更改所有者。这是为了确保系统的安全性。
//
// Created by zhangchuang on 2023/9/20.
//
/*
#include <unistd.h>
int chown(const char *pathname, uid_t owner, gid_t group);
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
const char *filename = "example.txt"; // 文件路径
uid_t new_owner = 1000; // 新所有者的用户ID
gid_t new_group = 1000; // 新组的组ID
// 使用chown函数更改文件的所有者和组
if (chown(filename, new_owner, new_group) == 0) {
printf("成功更改文件 %s 的所有者为 %d,组为 %d\n", filename, new_owner, new_group);
} else {
perror("chown"); // 输出错误信息
exit(EXIT_FAILURE);
}
return 0;
}
四、truncate
truncate
是一个系统函数,用于改变文件的大小。它通常在UNIX和类UNIX操作系统中使用。truncate
可以用来截断文件,使其更短或更长,或者用于创建一个大小为0的新文件。
//
// Created by zhangchuang on 2023/9/20.
//
/*
* #include <unistd.h>
#include <sys/types.h>
int truncate(const char *path, off_t length);
作用:
缩减或者扩展文件的尺寸到指定大小
参数:
-path:需要修改文件路径
-length: 需要最终文件变成的大小
返回值:
成功 0
失败 -1
*/
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
int main(){
int ret = truncate("b.txt",20);
if(ret==-1){
perror("truncate");
}
return 0;
}