gpt4 book ai didi

c - 如何设置输出文件模式权限(rw-rw-rw-)

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:07 28 4
gpt4 key购买 nike

我已经创建了一个代码,应该能够复制用户建议的文件。我想知道的是:如何设置输出文件模式以及如何确定此代码中的输出文件模式权限?

#include <stdio.h>
#include <stdlib.h>

int main()
{
char c;
char source_file, target_file;
FILE *in, *out;

printf("Enter name of file to copy\n");
gets(source_file);
printf("Enter name of file to copy to\n");
gets(target_file);
in = (source, O_RDONLY);
out = (target_file, O_CREAT|WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);

/* error handing */
if( in == NULL )
{
printf("Error. \n");
exit(0);
}

printf("Enter the copied file name \n");
gets(target_file);

out = fopen(target_file, "w");

/*error handing*/
if( out == NULL )
{
fclose(in);
printf("File opening error.\n");
exit(0);
}

while(( c = fgetc(in) ) != EOF )
fputc(c,out);

fclose(in);
fclose(out);

return 0;
}

最佳答案

使用标准 I/O 控制文件权限

标准 I/O 库的缺点之一是您无法控制所创建文件的权限,主要是因为此类权限是特定于平台的(无论如何比 C 标准所允许的要多) ). POSIX open()函数允许您在创建文件时控制文件的权限。

对于类似 POSIX 的系统,您可以使用 chmod()fchmod()系统调用。您需要知道您的 rw-rw-rw- 模式是八进制 0666。

chmod(target_file, 0666);
fchmod(fileno(out), 0666);

函数可能会失败;你应该检查他们是否没有。

您还可以使用 umask()功能或(小心)umask命令影响默认权限。例如,在 shell 中设置 umask 022 意味着将不会创建可由组或其他人写入的文件。


修改修改后的代码

  1. 您无需担心打开以供阅读的文件的权限(或者,至少,您很少需要这样做)。
  2. 担心您写入的文件的权限更为正常。
  3. 您当前的代码建议是:

    in = (source, O_RDONLY);
    out = (target_file, O_CREAT|WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);

    这不会调用 open(),而是将整数值分配给两个 FILE * 变量,这应该会生成编译器警告。请注意,逗号表达式计算表达式的 LHS,然后计算 RHS,生成 RHS 作为整体值。 O_RDONLY 通常为 0; S_IRUSR 等项的组合不为零。

如果你要用这些选项打开文件,那么你需要像这样的东西:

int fd_i = open(source_file, O_RDONLY);
if (fd_i < 0)
…report error opening source_file…
FILE *in = fdopen(fd_i, "r");
if (in == 0)
…report error creating file stream for source_file…

int fd_o = open(target_file, O_CREAT|WRONLY, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH);
if (fd_o < 0)
…report error opening target_file…
FILE *out = fdopen(fd_o, "w");
if (out == 0)
…report error creating file stream for target_file…

但是,我可能不会使用 fdopen()对于输入文件 — 我将像您最初那样直接使用 fopen() — 但我可能将它用于输出文件。

关于c - 如何设置输出文件模式权限(rw-rw-rw-),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25968289/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com