access ,chmod ,truncate

130 阅读2分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第33天,点击查看活动详情

chmod

在 Linux 系统中,"access" 指的是能够访问或使用某些内容的权限。 例如,您可能需要访问一个文件或文件夹,或者访问一个网站。访问权限通常是通过设置用户组或用户的访问权限来控制的。

#include<stdio.h>

/*int access(const char *pathname, int mode);
    mode :
        -R_OK, W_OK, and X_OK
        F_OK    tests for the existence of the  file.

*/

/*
    #include <unistd.h>
    int access(const char *pathname, int mode);
        作用:判断某个文件是否有某个权限,或者判断文件是否存在
        参数:
            - pathname: 判断的文件路径
            - mode:
                R_OK: 判断是否有读权限
                W_OK: 判断是否有写权限
                X_OK: 判断是否有执行权限
                F_OK: 判断文件是否存在
        返回值:成功返回0, 失败返回-1
*/

/*
    #include <sys/stat.h>
    int chmod(const char *pathname, mode_t mode);
        修改文件的权限
        参数:
            - pathname: 需要修改的文件的路径
            - mode:需要修改的权限值,八进制的数
        返回值:成功返回0,失败返回-1

*/
#include <sys/stat.h>
#include <stdio.h>
int main() {

    int ret = chmod("a.txt", 0777);

    if(ret == -1) {
        perror("chmod");
        return -1;
    }

    return 0;
}

chmod

chmod 是 Linux 命令行中用于更改文件或目录的权限的命令。

chmod 644 filename //只读 chmod 777 filename //读取写入执行

#include <sys/stat.h>
int chmod(const char *pathname, mode_t mode);

*/

#include <sys/stat.h>
#include<stdio.h>

int main() {
    int ret = chmod("a.txt", 0775);
    
    if (ret == -1) {
        perror("chmod");
        return -1;
    }
    return 0;
}

truncate

truncate 是 Linux 命令行中用于将文件或目录的长度截断为指定长度的命令。 在Linux下是这样解释的

The truncate() and ftruncate() functions cause the regular file named by path or referenced by fd to be truncated to a size of precisely length bytes.

   If the file previously was larger than this size, the extra data is lost.
   If the file previously was shorter, it is extended, and the extended part
   reads as null bytes ('\0').

   The file offset is not changed.
#include <sys/types.h>
#include <stdio.h>

int main() {

    int ret = truncate("b.txt", 5);

    if(ret == -1) {
        perror("truncate");
        return -1;
    }

    return 0;
}