1,open
SYNOPSIS
#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);
int creat(const char *pathname, mode_t mode);
参数解读
pathname文件路径名,flags文件打开的权限(只读O_RDONLY,只写O_RDONLY,可读可写O_RDWR),mode创建文件的模式(在第2个参数含有O_CREAT,才有第3个参数mode)
O_RDONLY,O_RDONLY,O_RDWR
打开/创建文件时,至少得使用上述三个常量中的一个。以下常量是选用的:
O_APPEND每次写操作都写入文件的末尾
O_CREAT如果指定文件不存在,则创建这个文件
O_EXCL如果要创建的文件已存在,则返回-1,并且修改errno的值
O_TRUNC如果文件存在,并且以只写/读写方式打开,则清空文件全部内容(即将其长度截短为0)
O_NOCTTY如果路径名指向终端设备,不要把这个设备用作控制终端。
O_NONBLOCK如果路径名指向FIFO/块文件/字符文件,则把文件的打开和后继I/O
第3个参数mode一般设置为可读可写0600,可读0400,可写0200
还有其他的宏:大佬的见解
DESCRIPTION
Given a pathname for a file, open() returns a file descriptor, a small, nonnega‐tive integer for use in subsequent system calls (read(2), write(2), lseek(2),fcntl(2), etc.). The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.
调用open(),creat()函数返回一个非负整数的文件描述符fd,open之后的read,write都是同通过文件描述符进行操作;creat函数只创建文件,read,write函数不能通过fd进行读写操作
2,write
函数原型
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count); 一个具有注脚的文本。[^w]
[^w]: fd文件描述符,buf写入的内容,count写入的字节数
PS:const修饰符const的作用及使用
3,read
函数原型
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);一个具有注脚的文本。[^r]
[^r]: fd文件描述符,buf读出内容的缓冲区,count读出的字节数
4,lseek(光标重定位)
函数原型
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
参数解读
fd文件描述符,offset相对whence偏移的字节数(负数向前移,正数向后移),whence光标所处位置。
PS:whence 有三个固定的宏:SEEK_SET文件头,SEEK_CUR当前光标位置,SEEK_END文件尾
lseek函数巧用——计算文件字节数
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main()
{
int fd;
int size;
fd = open("./file",O_RDWR);//打开文件光标默认在文件头
size = lseek(fd,0,SEEK_END);//让光标移到文件尾,返回的就是文件的字节数
printf("size:%d\n",size);
return 0;
}
运行结果
实现cp指令-mycp
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<stdlib.h>
int main(int argc,char **argv)
{
int fdsrc;
int fddes;
char *readbuff = NULL;
//判断参数
if(argc != 3){
printf("param error!\n");
exit(-1);
}
fdsrc = open(argv[1],O_RDWR);//打开源文件
int size = lseek(fdsrc,0,SEEK_END);//计算源文件大小
lseek(fdsrc,0,SEEK_SET);//把光标移回文件头
readbuff = (char*)malloc(sizeof(char)*size+8);//开辟缓冲区
read(fdsrc,readbuff,size);//将源文件读入缓冲区
fddes = open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0600);//创建目标文件
write(fddes,readbuff,size);//将缓冲区的内容写入目标文件
//关闭文件
close(fdsrc);
close(fddes);
return 0;
}
运行结果