C语言中的fchmod函数

3

程序:

#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__",但是它仍然保持旧的权限。为什么会这样?这段代码有任何错误吗?

3
啊咳嗽... void main()... - 3442
1
检查 fchmod 返回的值,如果失败则检查 errno - Some programmer dude
我测试了程序,所有的函数调用都返回零。 - 3442
实际上,在我的系统上,这很完美地运行。 - 3442
@JoachimPileborg 谢谢。我找到答案了。对于文件 b.txt,我没有为所有者设置读取权限。因此,在调用打开函数时,它没有权限打开 b.txt。所以,它会返回错误的文件描述符错误。所以,应该是这样的。 - mohangraj
4个回答

1

您没有修改文件的权限,请使用sudo调用您的程序以使其成功。

同时,始终检查诸如openfchmod之类的函数的返回值,并处理错误。


1
能否请给出负评的人解释一下为什么认为这个答案是错误的? - ouah

1
首先,您应该检查由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

你的程序可能缺少访问此文件的权限。

1
对于文件b.txt,我没有为所有者设置读取权限。因此,在调用open函数时,它没有打开b.txt的权限。因此,它返回了错误的文件描述符错误。所以,它会像这样。
程序:
#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
$

0

$ ls -l b.txt ----r----- 1 mohanraj mohanraj 0 Sep 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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接