一、open函数 打开及创建文件
函数原型及包含的头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, int flags);
参数1:const char *pathname,该文件路径名称;
参数2:int flags, 打开文件的三种模式O_RDONLY(可读), O_WRONLY(可写), or O_RDWR(可读可写),三者选其一;
另外,选择以上其中一个参数后还可以选以下参数:
O_CREAT 若文件不存在则创建它。使用此选项时,需同时说明参数3mode,其
说明该新文件的存取许可权限;
O_EXCL 如果同时指定了O_CREAT,而文件已经存在,则返回-1;
O_APPEND 每次写时都加到文件尾端;
O_TRUNC 属性去打开文件时,如果这个文件中本来是有内容的,而且为只读或者
只写成功打开,则将其长度截短为0。
3.返回值:如果文件成功创建或打开则返回文件对应的文件描述符(大于0的整数),否则返
回-1。(其中linux系统中默认0-标准输入,1-标准输出,2-标准错误)
代码实现
进入主函数,定义一个文件描述符fd并调用open函数,把open函数返回的文件描述符赋给fd,然后进行返回值判断,若返回值为-1,表示文件创建失败,此时再调用open函数(用O_CREAT)创建它,再一次判断返回值看是否创建成功。
二、write、read函数进行文件读写操作
函数原型及头文件
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
参数1:int fd,文件描述符即open函数的返回值;
参数2:const void *buf,写入到fd文件内容的写入缓冲区;
参数3:size_t count,要写入内容的字节数;
返回值:正确写入则返回写入字节大小,没有内容写入则返回0,错误写入则返回-1;
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
参数1:int fd,要读文件的文件描述符;
参数2:void *buf,存放读出来内容的缓冲区;
参数3:size_t count,从fd文件中读内容的字节大小;
返回值:正确读取则返回读取到内容的字节大小,没有内容则返回0,错误读取则返回-1;
三、lseek函数进行光标移动
函数原型及头文件
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
参数1:int fd,要操作文件的文件描述符;
参数2:off_t offset,光标的偏移量;偏移量为正数为往前偏移,负数为往后偏移
参数3:int whence,光标的起始位置;SEEK_SET文件头开始偏移 SEEK_END光标在 尾 SEEK_CUR 光标目前所在处
返回值:返回针对文件开头开始计算的偏移量,出错返回-1;
int filesize=lseek(fd,0,SEEK_END);//计算文件内字节大小
四、close函数关闭文件
函数原型及头文件
#include <unistd.h>
int close(int fd);
参数:int fd,要操作文件的文件描述符;
五、读写文件操作代码
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fd;
char *buf="zhengyanfeng handsome";
fd= open("./file1",O_RDWR);
if(fd == -1){
printf("open file1 fail\n");
fd= open("./file1",O_RDWR|O_CREAT,0600);
if(fd>0){
printf("creat file1 success\n");
}
}
printf("open success:fd=%d\n",fd);
int n_write= write(fd,buf,strlen(buf));
if(n_write != -1){
printf("write %d bytes to file\n",n_write);
}
char *readBuf;
readBuf=(char *)malloc(sizeof(char)*n_write+1);
lseek(fd,0,SEEK_SET);
read(fd,readBuf,n_write);
printf("read %d,context:%s\n",n_write,readBuf);
close(fd);
return 0;
}
编译实现