C 中的 fchmod 函数
fchmod function in C
节目:
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
void main()
{
int fd=open("b.txt",O_RDONLY);
fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
}
输出:
$ ls -l b.txt
----r----- 1 mohanraj mohanraj 0 Sep 12 15:09 b.txt
$ ./a.out
$ ls -l b.txt
----r----- 1 mohanraj mohanraj 0 Sep 12 15:09 b.txt
$
对于上述程序,我的预期输出是将 b.txt 的权限设置为 "rw_rw_r__"。但是,它仍然保留在旧的
允许。为什么会这样。这段代码有错误吗?
您没有修改文件的权限,请使用 sudo
调用您的程序以使其成功。
还要始终检查 open
和 fchmod
等函数的 return 值并处理错误。
首先,您应该检查 open
系统调用返回的 fd
是否正常,您还应该检查 fchmod
系统调用状态。
其次,我测试了您的示例代码,在我的例子中它的工作原理如下。
在 运行 你的程序之前:
pi@raspberrypi ~ $ ls -l hej.txt
-rw-r--r-- 1 pi pi 0 Sep 12 11:53 hej.txt
在 运行 你的程序之后:
pi@raspberrypi ~ $ ls -l hej.txt
-rwxrwxrw- 1 pi pi 0 Sep 12 11:53 hej.txt
您的程序可能缺少对此文件的权限。
对于文件b.txt,我没有设置所有者的读取权限。所以,当我们调用 open 函数时,它没有权限打开 b.txt。所以,它 returns 错误的文件描述符错误。所以,就会变成这样。
节目:
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
void main()
{
int fd=open("b.txt",O_RDONLY);
perror("open");
fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
perror("fchmod");
}
输出:
$ ./a.out
open: Permission denied
fchmod: Bad file descriptor
$
$ ls -l b.txt
----r----- 1 mohanraj mohanraj 0 9 月 12 日 15:09 b.txt
----r-----,表示b.txt的拥有者没有读写
的权限
$chmod 644 b.txt //add read and write Permission, -rw-r--r--
另外,更改文件权限需要O_RDWR标志
在继续之前确保功能成功
void main()
{
int fd=open("b.txt",O_RDWR);
if (fd > 0) {
//do some thing
}
}
节目:
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
void main()
{
int fd=open("b.txt",O_RDONLY);
fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
}
输出:
$ ls -l b.txt
----r----- 1 mohanraj mohanraj 0 Sep 12 15:09 b.txt
$ ./a.out
$ ls -l b.txt
----r----- 1 mohanraj mohanraj 0 Sep 12 15:09 b.txt
$
对于上述程序,我的预期输出是将 b.txt 的权限设置为 "rw_rw_r__"。但是,它仍然保留在旧的 允许。为什么会这样。这段代码有错误吗?
您没有修改文件的权限,请使用 sudo
调用您的程序以使其成功。
还要始终检查 open
和 fchmod
等函数的 return 值并处理错误。
首先,您应该检查 open
系统调用返回的 fd
是否正常,您还应该检查 fchmod
系统调用状态。
其次,我测试了您的示例代码,在我的例子中它的工作原理如下。
在 运行 你的程序之前:
pi@raspberrypi ~ $ ls -l hej.txt
-rw-r--r-- 1 pi pi 0 Sep 12 11:53 hej.txt
在 运行 你的程序之后:
pi@raspberrypi ~ $ ls -l hej.txt
-rwxrwxrw- 1 pi pi 0 Sep 12 11:53 hej.txt
您的程序可能缺少对此文件的权限。
对于文件b.txt,我没有设置所有者的读取权限。所以,当我们调用 open 函数时,它没有权限打开 b.txt。所以,它 returns 错误的文件描述符错误。所以,就会变成这样。
节目:
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
void main()
{
int fd=open("b.txt",O_RDONLY);
perror("open");
fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH);
perror("fchmod");
}
输出:
$ ./a.out
open: Permission denied
fchmod: Bad file descriptor
$
$ ls -l b.txt ----r----- 1 mohanraj mohanraj 0 9 月 12 日 15:09 b.txt
----r-----,表示b.txt的拥有者没有读写
的权限$chmod 644 b.txt //add read and write Permission, -rw-r--r--
另外,更改文件权限需要O_RDWR标志
在继续之前确保功能成功
void main()
{
int fd=open("b.txt",O_RDWR);
if (fd > 0) {
//do some thing
}
}