open用于打开一个文件,通过设置不同的flag,可以让进程只读,只写,可读/可写等操作
一、对一个不存在或者存在的文件(test.txt),进行写入操作
/*================================================================
* Copyright (C) 2018 . All rights reserved.
*
* 文件名称:cp.c
* 创 建 者:ghostwu(吴华)
* 创建日期:2018年01月10日
* 描 述:用open和write实现cp命令
*
================================================================*/ #include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h> int main(int argc, char *argv[])
{
int fd, openflags; //openflags = O_WRONLY | O_CREAT; openflags = O_WRONLY; fd = open( "test.txt" , openflags );
if( fd < ) {
printf( "%d\n", errno );
perror( "write to file" );
}
return ;
}
1)当test.txt不存在时, 文件打开失败,会把操作系统的全局变量errno设置一个错误号, 这里设置的是2,对于一个2,我们完全不知道是什么错误,所以调用perror函数,他会把编号2解释成可读性的错误信息,
那么这里被解读成"No such file or directory",可以通过"grep "No such file or directory" /usr/include/*/*.h" 找到errno为2对应的头文件
2)如果test.txt文件存在,不会报错,打开一个正常的文件描述符,文件原来的内容不会受影响
二、加入O_CREAT标志
/*================================================================
* Copyright (C) 2018 . All rights reserved.
*
* 文件名称:cp.c
* 创 建 者:ghostwu(吴华)
* 创建日期:2018年01月10日
* 描 述:用open和write实现cp命令
*
================================================================*/ #include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h> int main(int argc, char *argv[])
{
int fd, openflags; //openflags = O_WRONLY | O_CREAT; openflags = O_WRONLY | O_CREAT; fd = open( "test.txt" , openflags );
printf( "fd = %d\n", fd );
if( fd < ) {
printf( "%d\n", errno );
perror( "write to file" );
}
return ;
}
1)如果test.txt不存在,那就创建test.txt,不会报错
2)如果test.txt存在,test.txt原内容不会受到影响
三、加入O_TRUNC标志
openflags = O_WRONLY | O_CREAT | O_TRUNC;
1)如果test.txt不存在,那就创建test.txt,不会报错
2)如果test.txt存在,test.txt原内容会被清空
四、权限位
/*================================================================
* Copyright (C) 2018 . All rights reserved.
*
* 文件名称:cp.c
* 创 建 者:ghostwu(吴华)
* 创建日期:2018年01月10日
* 描 述:用open和write实现cp命令
*
================================================================*/ #include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h> int main(int argc, char *argv[])
{
int fd, openflags;
mode_t fileperms; openflags = O_WRONLY | O_CREAT | O_TRUNC; //rwxrw-r-x
fileperms = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IXOTH; fd = open( "test.txt" , openflags, fileperms );
printf( "fd = %d\n", fd );
if( fd < ) {
printf( "%d\n", errno );
perror( "write to file" );
}
return ;
}