一、打开文件
在Linux系统库的定义
int open(const char *pathname,int flags);//比较常用
int open(const char *pathname,int flags,mode_tmode);
//包含的头文件:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
返回值:
成功,返回句柄,我们后面对于文件的读写,关闭等都通过句柄来操作。
失败,返回-1
参数说明:
grep -nr "xxxx"./
pathname:文件的路径名,如果只写文件名,就默认当前目录,如果在文件名加上路径,就按照绝对路径来打开文件。
flags:表示打开文件后用的操作
底层是一个宏,它可能以十六进制的形式存放。
O_RDONLY:只读模式 0x 0000 0000
O_WRONLY:只写模式 0x 00000001
O_RDWR :可读可写 0x 00000002
1.采用路径的形式打开文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd;//file describe
fd = open("/home/zmk/mm",O_RDONLY);
if(fd == -1)
{
printf("open failed! \r\n");
return -1;
}
printf("open successed!\r\n");
return 0;
}
~
2.以操作文件名打开文件 如果只写文件名,就默认当前目录
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd;//file describe
fd = open("mm",O_RDONLY);
if(fd == -1)
{
printf("open failed! \r\n");
return -1;
}
printf("open successed!\r\n");
return 0;
}
~
参数说明:
O_APPEND 表示追加,如果原来文件里面有内容,则这次写入会写在文件的最末尾0x00002000
O_CREAT 表示如果指定文件不存在,则创建这个文件 0x0000 0100
O_EXCL 表示如果要创建的文件已存在,则出错,同时返回-1,并且修改errno 的值。
O_TRUNC 表示截断,如果文件存在,并且以只写、读写方式打开,则将其长度截断为0。
O_NOCTTY 如果路径名指向终端设备,不要把这个设备用作控制终端
3.如果文件中没有该文件夹可通过O_CREAT指令创建出该文件夹
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
int fd;
fd = open("mm",O_RDONLY|O_CREAT);
if(fd == -1)
{
printf("open failed!\r\n");
return -1;
}
printf("open successed!\r\n");
return 0;
}
二、关闭文件
在Linux系统库的定义: int close(int fd);
包含的头文件 #include <unistd.h>
功能就是简单的关闭文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
int fd;
fd = open("mm",O_RDONLY|O_CREAT);
if(fd == -1)
{
printf("open failed!\r\n");
return -1;
}
printf("open successed!\r\n");
close(fd);
return 0;
}