【发布时间】:2018-05-28 14:49:55
【问题描述】:
我必须在 c create 中编写一个带有 2 个参数的函数:文件名和文件权限。 (例如:create("f","rwxr_xr_x") 此函数创建文件 f,该文件将获得 "rwxr_xr_x" 权限并将返回 0)如果文件已存在或无法创建,它将返回一个不同于 0 的数字。 这是我想出的代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
int create(char *name, char *mode)
{
int fp = fopen(name, "r+");
if (fp > 0)
{
int i, n = 0;
for (i = 0; i < 9; i = i + 3)
{
int nr = 0;
if (mode[i] == 'r') nr += 4;
if (mode[i + 1] == 'w') nr += 2;
if (mode[i + 2] == 'x') nr += 1;
n = n * 10 + nr;
}
chmod(name, n);
return 0;
}
else
return -1;
}
int main(int argc, char* argv[])
{
if (argc != 3) printf("%s\n", "Error: Incomplet number of arguments!");
int fp;
fp = create(argv[1], argv[2]);
if (fp == 0) printf("%s\n", "File successfully created!");
else printf("%s\n", "Could not create file!");
return 0;
}
我尝试以 r+ 模式打开文件,然后使用 chmod 更改权限,{不确定这是否正确)。当我编译这个时,我收到以下警告:“初始化从指针中生成整数,而不对行 int fp=fopen(name, r+) 进行强制转换。有人可以帮我解决这个问题并告诉我代码是否正确吗?我是 linux 新手
更新 所以我按照建议进行了一些更改,但我认为它仍然没有提供正确的权限(正如我所说我是 linux 新手,所以我可能错了)。这是我的代码现在的样子:
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
int create(char *name, char *mode)
{
int i,n=0;
for(i=0; i<9; i=i+3)
{
int nr=0;
if(mode[i]=='r') nr+=4;
if(mode[i+1]=='w') nr+=2;
if(mode[i+2]=='x') nr+=1;
n=n*8+nr;
}
int fl=creat(name, n);
printf("%d\n", n);
if(fl>0)
return 0;
else return -1;
}
int main(int argc, char* argv[])
{
if(argc != 3)
printf("%s\n", "Error: Incomplet number of arguments!");
int fp;
fp=create(argv[1], argv[2]);
if(fp==0) printf("%s\n", "File successfully created!");
else printf("%s\n", "Could not create file!");
return 0;
}
另外,如何检查文件是否已经存在?因为在这种情况下,我的函数必须返回一个不同于 0 的值并打印错误消息
【问题讨论】:
-
fopenreturns aFILE *not an int,openreturn anint -
@PawanKartik:问题与创建文件而不是目录有关。
-
@Alexandra_p:有什么理由不使用open/creat?
-
ITYM
n = n * 8 + nr,因为您在那里使用八进制。 -
@TobySpeight 感谢您的建议,我更改了它但仍然不确定它是否有效?
标签: c linux file permissions chmod