C语言 使用 C 在 Linux 中创建文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2395465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 04:45:13  来源:igfitidea点击:

Create a file in Linux using C

c

提问by michael

I am trying to create a write only file in C on Linux (Ubuntu). This is my code:

我正在尝试在 Linux (Ubuntu) 上用 C 创建一个只写文件。这是我的代码:

 int fd2 = open ("/tmp/test.svg", O_RDWR|O_CREAT);

 if (fd2 != -1) {
   //....
 }

But why do the files I created have 'xr' mode? How can I create it so that I can open it myself at command prompt?

但是为什么我创建的文件有“xr”模式?如何创建它以便我可以在命令提示符下自己打开它?

------xr--  1 michael michael  55788 2010-03-06 21:57 test.txt*
------xr--  1 michael michael   9703 2010-03-06 22:41 test.svg*

回答by Jonathan Leffler

You need the three-argument form of open()when you specify O_CREAT. When you omit the third argument, open()uses whatever value happens to be on the stack where the third argument was expected; this is seldom a coherent set of permissions (in your example, it appears that decimal 12 = octal 014 was on the stack).

open()指定 O_CREAT 时需要三参数形式。当您省略第三个参数时,open()使用堆栈上恰好出现第三个参数的任何值;这很少是一组连贯的权限(在您的示例中,十进制 12 = 八进制 014 似乎在堆栈中)。

The third argument is the permissions on the file - which will be modified by the umask()value.

第三个参数是文件的权限 - 它将被umask()值修改。

int fd2 = open("/tmp/test.svg", O_RDWR | O_CREAT, S_IRUSR | S_IRGRP | S_IROTH);

Note that you can create a file without write permissions (to anyone else, or any other process) while still being able to write to it from the current process. There is seldom a need to use execute bits on files created from a program - unless you are writing a compiler (and '.svg' files are not normally executables!).

请注意,您可以在没有写入权限的情况下创建文件(对其他人或任何其他进程),同时仍然可以从当前进程写入文件。很少需要在从程序创建的文件上使用执行位 - 除非您正在编写编译器(并且“.svg”文件通常不是可执行文件!)。

The S_xxxx flags come from <sys/stat.h>and <fcntl.h>— you can use either header to get the information (but open()itself is declared in <fcntl.h>).

S_xxxx 标志来自<sys/stat.h><fcntl.h>- 您可以使用任一标头来获取信息(但open()它本身在 中声明<fcntl.h>)。

Note that the fixed file name and the absence of protective options such as O_EXCLmake even the revised open()call somewhat unsafe.

请注意,固定的文件名和缺少保护选项(例如,O_EXCL即使修改后的open()调用也有些不安全)。

回答by kompally santosh

Give access permissions as the third parameter:

授予访问权限作为第三个参数:

int fd2 = open("/tmp/test.svg", O_RDWR|O_CREAT, 0777);  // Originally 777 (see comments)

if (fd2 != -1) {
    // use file descriptor
    close(fd2);
}

By doing this, all read, write and execute permissions will be given to user, group and others. Modify the 3rd parameter according to your use.

通过这样做,所有读取、写入和执行权限都将授予用户、组和其他人。根据您的使用修改第三个参数。