您的位置:首页 > 运维架构 > Linux

linux 学习笔记(三):open、creat、close 函数的使用,文件的创建、打开与关闭

2016-05-24 07:28 886 查看
<span style="font-size:14px;">参考书籍:linux c编程实战  百度云下载链接: http://pan.baidu.com/s/1c2iD3X2 密码: wshq</span>

自学中,看着这本书的pdf文件编程,由于之前学过c语言,所以c语言部分简单的复习了一下直接跳到了linux下c语言的编程。

本次主要学习了三个函数open、creat、close。详细了解函数的使用可以在shell下输入man 函数名 查看详细说明。。。。啥是shell 对于我这个小白来说 就是终端下直接输入命令就好了。。。。


在用 man open 时候发现出现的函数不是我想要的open而是一个openvt的函数,百度结果 原来是有两个手册,查看open函数需要输入 man 2 open;

这个函数的使用需要包含三个头文件

#include <sys/types.h>

#include <sys/stat.h>

#include <fcntl.h>

open函数:

1.int open(const char *pathname, int flags);

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

参数 ×pathname :带路径的文件名,例题中的“example_62.c" 应该要打开或者创建的文件名字。

参数 flags:选项比较多,可以通过shell下的man 2 open 查看参数的具体意思

O_CREAT:如果文件不存在则创建文件,如果填本参数,则2函数中第三个参数也要填,第三个参数主要限定用户对文件的操作权限权限

O_EXCL:这个参数在man 2 open 下原文是 Ensure that this call creates the file: if this flag is specified in conjunction with O_CREAT, and pathname already exists,then open() will
fail 。 In general, the behavior of O_EXCL is undefined if it is used without O_CREAT. 这个参数应该是确保这个文件被创建,如果这个文件存在则调用open函数失败,并且这个参数必须和 O_CREAT结合使用,但是在2.6及以后的内核版本中如果本参数是关于块设备路径文件名可以单独使用。(前面还能看得懂,关于内核和块设备啥的没有一点概念



O_TRUNC:如果这个文件已经存在并且为 可读可写/只写 这个文件内容将被清零

其它的值本例子木有用的到,也懒得去查等用到了再去详细了解。。。。。。

creat函数:

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

在open函数的解释中 有creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC.应该说的是这个函数的功能等于open()函数的flag参数为 O_CREAT|O_WRONLY|O_TRUNC 时的功能。

close函数:

int close(int fd);

这个函数只有一个参数 这个参数为需要关闭文件的描述符调用成功返回0错误的返回-1

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
int main()
{
int fd;
if((fd = open("example_62.c",O_CREAT|O_EXCL,S_IRUSR| S_IWUSR)) == -1)
{
//      if((fd= creat("example_62.c",S_IRWXU)) == -1)
perror("open");
//              printf("open%s    with errno:%d\n",strerror(errno),errno);
exit(1);
}
else
printf("create file success\n");
close(fd);
return 0;
}

本例子除了上述三个函数还有一个 perro函数和strerror函数

perror 函数 描述: The perror() function produces a message on standard error describing the last error encountered during a call to a system or library function.百度百科上是这样解释的:perror(s) 用来将上一个函数发生错误的原因输出到标准设备(stderr)。参数
s 所指的字符串会先打印出,后面再加上错误原因字符串。此错误原因依照全局变量errno(这里的说法不准确,errno是一个宏,该宏返回左值) 的值来决定要输出的字符串。在库函数中有个errno变量,每个errno值对应着以字符串表示的错误类型。当你调用"某些"函数出错时,该函数已经重新设置了errno的值。perror函数只是将你输入的一些信息和现在的errno所对应的错误一起输出。运行上述例子,在要创建的文件已经存在的情况下shell下输出:open: File exists

strerror 函数则是吧error对应的描述符转化为对应的字符串 例如error值为17 则 strerror(error)返会17这个描述符对应的字符串 本例子为 file exist
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: