编写Linux C程序,列出stu2主目录中的文件信息,并将其中saturday.txt文件的权限设置为文件所有者可读可写、同组用户只读、其他用户无权限。
时间: 2024-03-05 19:52:24 浏览: 52
您可以使用Linux系统的系统调用函数来实现这个功能,下面是一个简单的示例程序:
```c
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
char *dir_path = "/home/stu2"; // stu2主目录的路径
DIR *dir = opendir(dir_path); // 打开目录
if (dir == NULL) {
perror("opendir failed");
return -1;
}
struct dirent *dp;
while ((dp = readdir(dir)) != NULL) { // 遍历目录
if (dp->d_name[0] == '.') continue; // 忽略隐藏文件
printf("%s\n", dp->d_name);
}
closedir(dir); // 关闭目录
char *file_path = "/home/stu2/saturday.txt"; // saturday.txt的路径
struct stat st;
if (stat(file_path, &st) != 0) { // 获取文件状态
perror("stat failed");
return -1;
}
mode_t new_mode = (st.st_mode & ~S_IWOTH) | S_IRUSR | S_IWUSR | S_IRGRP; // 新的文件权限
if (chmod(file_path, new_mode) != 0) { // 设置文件权限
perror("chmod failed");
return -1;
}
return 0;
}
```
需要注意的是,这个程序需要以root权限运行才能修改文件权限。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)