创建使用C Linux的文件 [英] Create a file in Linux using C

查看:70
本文介绍了创建使用C Linux的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个只写在C文件在Linux(Ubuntu的)。
这是我的code:

  INT FD2 =打开(/tmp/test.svg,O_RDWR | O_CREAT); 如果(FD2!= -1){
   // ....
 }

可是为什么我创建的文件有XR模式?如何创建它,这样我可以在命令提示符下打开它自己吗?

  ------ xr-- 1迈克尔·迈克尔·55788 2010-03-06 21:57 test.txt的*
------ xr-- 1迈克尔·迈克尔·9703 2010-03-06 22:41 test.svg *


解决方案

您需要的 的open() 当指定O_CREAT。如果省略第三个参数,的open()使用任何值正好是那里的第三个参数,预计在栈中;这是很少一套连贯的权限(在你的榜样,似乎十进制12 = 014八是在栈上)。

第三个参数是该文件的权限 - 这将是由的umask被修改()

  INT FD2 =打开(/ tmp目录/ test.svg,O_RDWR | O_CREAT,S_IRUSR | S_IRGRP | S_IROTH);

请注意,你可以创建一个没有写入权限的文件(给其他人,或任何其他进程),同时还能够从当前进程写入。有很少需要使用从程序创建的文件执行位 - 除非你正在编写一个编译器(和'.SVG文件无法正常可执行文件!)

该S_xxxx标记来自 &LT ; SYS / stat.h> 和的 < fcntl.h> - 您可以使用头得到的信息(但的open()本身声明< fcntl.h方式>

请注意,固定的文件名和缺乏保护选项,如 O_EXCL 让即使是修订后的的open()打电话有点不安全。

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

 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--  1 michael michael  55788 2010-03-06 21:57 test.txt*
------xr--  1 michael michael   9703 2010-03-06 22:41 test.svg*

解决方案

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).

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

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!).

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>).

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

这篇关于创建使用C Linux的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆