1.open
需要的头文件
前三个是open()
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
close()
#include<unistd.h>
perror()
#include<stdio.h>
打开以存在的文件:int open(const char *pathname, int flags);
当文件不存在时返回-1,pathname 表示文件的路径,flags表示需要的操作,O_RDONLY只读(read-only)O_WRONLY 只写(write-only), O_RDWR读写(read/write)
在当前目录下打开a.txt文件,若改文件不存在输出 open:,若存在则输出文件描述符
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<unistd.h>
#include<stdio.h>
int main()
{
int fd = open("a.txt",O_RDONLY);
if(fd == -1){
perror("open");
}
printf("%d \n",fd);
close(fd);
return 0;
}
创建文件:int open(const char *pathname, int flags, mode_t mode);
O_CREAT 表示创建一个新文件
mode 表示创建的文件的权限,传入的需要是八进制的值,umask默认值为0002,权限的最终由mode和umask确定
(mode & ~umask)
创建的text.txt文件被赋予了可执行的权限,可以通过调节umask的值来控制文件的权限
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include<stdio.h>
int main()
{
int fd = open("text.txt",O_RDONLY | O_CREAT,0777);
if(fd == -1){
perror("open:");
}
printf("%d\n",fd);
close(fd);
return 0;
}
ssize_t read(int fd, void *buf, size_t count);
fd:读取文件描述符,
buf:需要读取数据存放的地方,数组的地址(传出参数)
count:指定的数组的大小
返回值:-1 读取失败;
0 达到文件末尾
> 0 读取的字节数;
ssize_t write(int fd, const void *buf, size_t count);
fd:写入文件描述符,
buf:需要写入的数据,
count:要写的数据的实际的大小
成功:实际写入的字节数
失败:返回-1
将source.txt文件的内容复制到cpy.txt中
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
int srcfd = open("source.txt",O_RDONLY);
if(srcfd == -1)
{
perror("open source.tex: ");
exit(-1);
}
int copyfd = open("cpy.txt", O_WRONLY | O_CREAT, 0664);
if(copyfd == -1)
{
perror("open:");
exit(-1);
}
char buf[1024] = {0};
int len = 0;
while((len = read(srcfd,buf,sizeof(buf))) >0)
{
write(copyfd,buf,len);
}
close(srcfd);
close(copyfd);
return 0;
}