一、Linux文件编程 |
您所在的位置:网站首页 › open函数返回的文件描述符数据类型为 › 一、Linux文件编程 |
目录 一、open函数使用的介绍 函数功能: 返回值: open使用一 (两个参数) 代码演示: 运行结果: open使用二(三个参数) 0600权限的意思是可读可写, 代码演示: linux终端shell查看当前文件夹下的所有文件清单权限指令 ls -l 二,creat函数的使用介绍 函数功能: 函数返回值: 函数参数: creat使用: 代码演示: 三、关于open、creat函数文件描述符的描述 四、关于Linux文件编程的一般步骤 五、Linux文件管理简述 一、open函数使用的介绍#include #include #include 头文件 1. int open(const char *pathname, int flags); 2. int open(const char *pathname, int flags, mode_t mode); 当进程打开文件的时候,会建立结构体对这些文件进行管理,文件描述符会指向内核中的结构题体,对这些文件起到索引作用 函数功能:打开或创建某个文件 返回值:调用成功返回一个大于0的数字,这个数字是文件描述符。(后续对打开或创建的文件,进行读或写的操作时候都需要用到这个文件描述符)。调用失败返回-1。 open使用一 (两个参数)当我们需要打开的文存在的时候使用 int open(const char *pathname, int flags); 有两个参数: 第一个参数:const char *pathname 需要打开文件路径名字 第二个参数:int flags 对打开的文件的操作权限 O_RDONLY 只读打开 O_WRONLY 只写打开 O_RDWR 可读可写打开 代码演示: #include #include #include #include int main() { int fd; fd = open("./file",O_RDWR); //用可读可写O_RDWR的方式打开当前文件夹下的./file文件 printf("fd = %d\n",fd); return 0; } 运行结果: ./a.out //程序运行 fd = 3 //文件描述符=3 open使用二(三个参数)当我们打开的这个文件不存在的时候,要创建这个文件,可以是使用三个参数的open int open(const char *pathname, int flags, mode_t mode); 第二个参数 Flags: O_RDONLY 只读打开 O_WRONLY 只写打开 O_RDWR 可读可写打开 当我们附带了权限后,打开的文件就只能按照这种权限来操作。 以上这三个常数中应当只指定一 个。下列常数是可选择的: O_CREAT 若文件不存在则创建它。使用此选项时,需要同时说明第三个参数mode,用其说明该新文件的存取许可权限。 O_EXCL 如果同时指定了OCREAT,而文件已经存在,则出错。 O_APPEND 每次写时都加到文件的尾端。 O_TRUNC 属性去打开文件时,如果这个文件中本来是有内容的,而且为只读或只写成功打开,则将其长度截短为0。 Mode:一定是在flags中使用了O_CREAT标志,mode记录待创建的文件的访问权限 0600权限的意思是可读可写,可读r = 4 可写w = 2 可执行x = 1 所以4+2 = 6 -------> 0600 可读可写权限 代码演示: #include #include #include #include int main() { int fd; fd = open("./file",O_RDWR); //可读可写O_RDWR方式,打开file文件 if(fd == -1){ //判断是否打开失败 fd = open("./file",O_RDWR|O_CREAT,0600); //打开失败,那就创建这个文件,给与0600权限可读可写。 if(fd > 0){ //再次判断是否文件是否创建成功 puts("success create"); }else{ puts("creation failure"); } } printf("fd = %d\n",fd); //打印文件描述符 return 0; } ~ ~ linux终端shell查看当前文件夹下的所有文件清单权限指令 ls -l 二,creat函数的使用介绍#include #include #include //头文件的包含 int creat(const char *pathname, mode_t mode); //函数原型 函数功能:creat函数功能与open函数功能类似,creat函数功能是创建文件 函数返回值:creat函数调用成功返回一个文件描述符,调用失败返回-1 函数参数:a. const char *pathname :要创建的文件名字(包含文件的路径,不写则为当前路径下创建) b.mode_t mode :表示文件的创建模式 creat使用: 代码演示: #include #include #include #include #include #include #include int main() { int fd; fd = creat("/home/CLC/create",S_IRWXU);//在这个路径下/home/CLC/创建create文件,权限可读可写可执行 printf("creat fd = %d \n",fd); close(fd); return 0; } 三、关于open、creat函数文件描述符的描述 四、关于Linux文件编程的一般步骤 五、Linux文件管理简述 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |