加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用open()在C中创建文件

发布时间:2020-12-16 09:56:25 所属栏目:百科 来源:网络整理
导读:这是我第一次使用open(): #include fcntl.h 我正在尝试创建两个文件: int fd;int fd2;char *tmpname = "./TMPFILE";printf( "Temporary file createdn ");char *tmpname2 = "./TMPFILE2";printf( "Temporary file two createdn ");fd = open(tmpname,O_W
这是我第一次使用open():

#include <fcntl.h>

我正在尝试创建两个文件:

int fd;
int fd2;
char *tmpname = "./TMPFILE";
printf( "Temporary file createdn ");
char *tmpname2 = "./TMPFILE2";
printf( "Temporary file two createdn ");
fd = open(tmpname,O_WRONLY | O_APPEND);
fd2 = open(tmpname2,O_WRONLY | O_APPEND);

我正在尝试在当前工作目录中创建可以写入和追加的文件.

这编译并运行,但我担心的是,当我检查我的目录以查看文件是否已创建时,它们未列出.

我的问题是open()只生成程序运行后删除的临时文件,还是我搞砸了什么?

解决方法

创建文件时,需要打开第三个参数(模式).如果你不这样做,就会发生不可预测的事情.

此外,如果您想创建一个文件,如果它不在那里,您将需要O_CREAT或者进入,即

fd = open(tmpname,O_WRONLY | O_APPEND | O_CREAT,0644);

如果文件不存在,O_CREAT(粗略地说)会创建该文件.

从手册页:

NAME
       open,creat - open and possibly create a file or device

SYNOPSIS
       #include 
       #include 
       #include 

       int open(const char *pathname,int flags);
       int open(const char *pathname,int flags,mode_t mode);

       int creat(const char *pathname,mode_t mode);

...
       O_CREAT
              If the file does not exist it will be created.  The owner (user ID) of
              the  file  is  set to the effective user ID of the process.  The group
              ownership (group ID) is set either to the effective group  ID  of  the
              process  or  to  the  group  ID  of the parent directory (depending on
              filesystem type and mount options,and the mode of the  parent  direc                        

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读