【发布时间】:2020-08-22 23:59:00
【问题描述】:
我的目的是打开两个文件,其中第二个是全新的,具有与第一个文件相同的权限。因此,为了测试我的代码,我将第一个文件权限更改为“777”。然后我开始运行我的程序。令我惊讶的是,新生文件2的权限是错误的!它们设置为 755。更奇怪的是,当我将第一个文件设置为“111”并再次尝试时,结果现在是“1204”。 有人可以向我解释一下这种奇怪的行为吗?
这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(int argc, char *args[]) {
struct stat stats;
int fd1, fd2;
fd1 = open("testfile.txt", O_RDONLY);
/* Error check*/
if (fd1 == -1) {
/* Error handling */
perror("Opening");
printf("Unable to open file: %s\n", "testfile.txt");
printf("ERROR: %s\n", strerror(errno));
return 1;
}
if(fstat(fd1, &stats) == -1)
{
printf("Error while getting stats: %s\n", strerror(errno));
exit(-1);
}
//Receives the output file as a main argument . . .
if (argc > 1)
{
//(stats.st_mode = Gets the mask of the first file)
fd2 = open(args[1], O_WRONLY|O_CREAT, stats.st_mode);
/* Error check*/
if (fd2 == -1) {
/* Error handling */
perror("Opening");
printf("Unable to open file: %s\n",args[1]);
printf("ERROR: %s\n", strerror(errno));
return 1;
}
}
//. . . if it doesn't it creates a standard one warning you about it
else
{
fd2 = open("Nope.txt", O_WRONLY|O_CREAT, stats.st_mode);
/* Error check*/
if (fd2 == -1) {
/* Error handling */
perror("Opening");
printf("Unable to open file: %s\n",args[1]);
printf("ERROR: %s\n", strerror(errno));
return 1;
}
printf("Standard file created\n");
}
close(fd1);
close(fd2);
return 0;
}
我尽量让它整洁:)
【问题讨论】:
-
您是否在所有正确的位置正确地在不同的碱基之间进行转换? oct1204和dec644一样,都是rw- r-- r--,比较典型的权限。
-
是否允许覆盖卷的
group和other权限? -
您好,有趣的是,
st_mode字段还包含其他标志。要将其转换为open可以使用的文件模式,可能会感兴趣:stackoverflow.com/questions/11669504/… -
@Thomas Jager 是的,八进制;
-
@Weather Vane 对不起,我什至不知道这个比赛的音量是什么意思;
标签: c file permissions system-calls