我希望我的程序执行以下操作: 1)创建一个名为filename.txt的文件 2)分配777的权限 3)将“这将输出到testfile.txt \ n”写入新创建的文件
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#define PERMS 0777
int main(int argc, char *argv[])
{
int createDescriptor;
int openDescriptor;
char fileName[15]="Filename.txt";
if ((openDescriptor = open(fileName, O_CREAT | O_WRONLY )) == -1)
{
printf("Error creating %s\n", fileName);
exit(EXIT_FAILURE);
}
umask(0000);
if ((openDescriptor = creat(fileName, PERMS )) == -1)
{
printf("Error creating %s", fileName);
exit(EXIT_FAILURE);
}
if(write(openDescriptor,"This will be output to testfile.txt\n",36 ) != 36)
{
write(2,"There was an error writing to testfile.txt\n",43);
return 1;
}
if((close(openDescriptor))==-1)
{
write(2, "Error closing file.\n", 19);
}
return 0;
}
答案 0 :(得分:1)
你做错了。
只需执行int openDescriptor = creat(fileName, PERMS);
即可创建并打开文件并输入正确的权限。如果文件已存在,则调用不会失败。
最后,请写下:write(openDescriptor, ...);
对于记录,您不应将777用作文件模式。出于安全原因,不建议这样做。