open函数

//open()

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <errno.h>

#include <stdio.h>

#include <string.h>

#include <unistd.h>

int main()

{

int fd =0;

// O_RDONLY,O_WRONLY,O_RDWR

//只读打开,若文件不存在不会自动创建文件,打开失败

//fd=open("test.dat",O_RDONLY);

//只读打开,若文件不存在则创建,并需要说明其权限    "|"----->位或符号  U--->user;GRP--->组,团体;OTH--->其它

// fd =open("test.dat",O_RDONLY | O_CREAT,S_IRWXU|S_IRGRP|S_IROTH);

// 只写打开,若文件不存在则打开失败

// fd =open("test.dat",O_WRONLY);

// O_EXCL:一般和O_CREAT配合使用,若文件存在,则创建失败

fd =open("test.dat",O_WRONLY | O_CREAT|O_EXCL,S_IRUSR|S_IWUSR|S_IWGRP|S_IROTH);

if (-1==fd)

{

printf("errno=%d\n",errno);

printf("strerr:%s\n",strerror(errno));

}

else

{

printf("open flie ok\n");

char *pData ="hello world";

int ret=0;

ret =write(fd,pData,strlen(pData));

if( 0< ret)

{

printf("write data ok");

}

else

{

printf("write has some thing unknow\n");

}

close(fd);

}

return 0;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容