文件操作函数
这一节主要讲解最基础的打开文件,读写文件,关闭文件三个函数吗,以及其对对应的demo例程。
目录
文件操作函数
打开文件
DEMO
读写文件
关闭文件
函数例程
DEMO
—open函数
int open(const char *pathname, int flags)
int open(const char *pathname, int flags, mode_t mode)
pathname—文件名
flags—文件执行权限—— O_RDonLY 只读、O_WRonLY 只写、O_RDWR 读写
O_CREAT 创建 O_APPEND 文件结尾 O_TRUNC 截断文件 O_NonBLOCK 非阻塞
mode—创建的文件权限 umask & mode
成功返回文件描述符(整数),失败返回 -1 并设置 errno
DEMO
#include //Standrad c program library head file
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
int fd; //file descriptor
fd = open("file",O_RDWR); //Open the file to read/write
if(fd == -1 ){
fd = open("file",O_RDWR|O_CREAT,0641); //If file not exist, creat file
if(fd == -1){
perror("open errno"); //if creat file failed, printf mistake
exit(1);
}
printf("creat success! file fd = %dn",fd); //creat file success, printf file descriptor
}else{
printf("open file success! fd = %dn",fd); //open file success
}
close(fd); //close file
return 0;
}
读写文件
—read/write函数
ssize_t read(int fd, void *buf, size_t count)
ssize_t write(int fd, const void *buf, size_t count)
fd—文件描述符(open文件成功的返回值)
buf—读/写缓冲区
count—读/写文件的大小
成功返回读/写文件的字节数,返回0表示读/写完,失败返回 -1 并设置 errno
光标定位
—lseek函数
off_t lseek(int fd, off_t offset, int whence);
fd—文件描述符(open文件成功的返回值)
offset—文件相对偏移量
whence— 偏移起始位置,SEEK_SET—从头偏移 SEEK_CUR—从当前位置偏移
SEEK_END—从文件末尾偏移
成功返回,返回从文件头偏移的字节数,失败返回 -1 并设置 errno
光标定位—read/write函数
ssize_t read(int fd, void *buf, size_t count)
ssize_t write(int fd, const void *buf, size_t count)
fd—文件描述符(open文件成功的返回值)
buf—读/写缓冲区
count—读/写文件的大小
成功返回读/写文件的字节数,返回0表示读/写完,失败返回 -1 并设置 errno
—lseek函数
off_t lseek(int fd, off_t offset, int whence);
fd—文件描述符(open文件成功的返回值)
offset—文件相对偏移量
whence— 偏移起始位置,SEEK_SET—从头偏移 SEEK_CUR—从当前位置偏移
SEEK_END—从文件末尾偏移成功返回,返回从文件头偏移的字节数,失败返回 -1 并设置 errno
DEMO
#include关闭文件//Standrad c program library head file #include #include #include #include #include #include #include int openFile(const char *pathname) { int fd; fd = open(pathname,O_RDWR); //Open the file to read/write if(fd == -1 ){ perror("open errno"); //if open file failed, printf mistake return -1; }else{ return fd; } } int main(int argc, char *argv[]) { int fd; //file descriptor char *str = "heelo,word!"; char buf[1024] = {' '}; fd = openFile("file"); //open file int n_write = write(fd,str,strlen(str)); //write str to an open file if(n_write == -1){ perror("write errno"); //write file failed exit(1); } printf("write file success!n"); //write file success lseek(fd,-n_write,SEEK_CUR); //让光标从新定位到文件开头 int n_read = read(fd,buf,n_write); if(n_read == -1){ perror("read errno"); exit(1); } printf("file size:%d file data:%sn",n_read,buf); //printf file size and content's close(fd); //close file return 0; }
—close函数
int close(int fd)
fd—文件描述符(open文件成功的返回值)
成功返回 0,失败返回 -1 并设置 errno
函数例程
由过以上三个文件操作函数我们来编写一个demo实现cp-shell指令功能



