open函数
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
打开已存在的文件
int open(const char *pathname, int flags);
创建一个新文件
int open(const char *pathname, int flags, mode_t mode);
返回值是指向被打开文件的文件描述符,如果发生错误返回-1,产生errno
参数:
-flags:(O_RDONLY O_WRONLY O_RDWR这三个互斥的,含义分别是只读,只写,可读可写)
可选项:O_CREAT 创建新文件的必选项
-mode:设置文件权限,如设置rwxrwxrwx,mode为0777
文件的最终权限为mode&~umask (umask的默认值为0002一般用户)
read函数
#include <unistd.h>
读取文件,输入操作(内存角度)
ssize_t read(int fd, void *buf, size_t count);
返回值为实际读取到的字节数
参数:
-count 表示想要读取到的字节数
-buf 一般为字符数组,用来存放从文件读取到的数据
write函数
#include <unistd.h>
写入文件,输出操作(内存角度)
ssize_t write(int fd, const void *buf, size_t count);
返回值为实际写入的字节数
参数:
-count 表示想要写入的字节数
-buf 用来存放 将要输出到文件的 数据
perror函数
与文件操作配套使用
#include <stdio.h>
根据errno打印错误信息
void perror(const char *s);
参数:
-s:用户设定,一般用来显示哪个函数发生错误
如果是open发生错误,perror(“open”)
下面是对上面几个函数介绍的一个示例
程序作用是从已有文件english.txt中读取全部字节,然后写入到新文件cpy.txt中(cpy.txt是原本不存在的,通过这个程序创建)
示例:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <iostream>
using namespace std;
int main(){
int srcfd =open("english.txt",O_RDONLY);//打开已有文件
if(srcfd == -1){
perror("open");
return -1;
}
int fd = open("cpy.txt",O_WRONLY|O_CREAT,0664);//创建新文件,设置权限为rw_rw_r__
if(fd == -1){
perror("open");
return -1;
}
char buf[1024] ={0};
int len = 0;
while((len = read(srcfd,buf,sizeof(buf)))>0){//从english.txt中读取数据
cout<<write(fd,buf,len)<<endl;//写入cpy.txt
}
close(srcfd);
close(fd);
return 0;
}