一、文件的打开与创建
1、函数使用
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
int main()
{
int fd ;//文件打开会返回一个文件按描述符,用于后续操作
fd = open("./file",O_RDWR|O_CREAT,0600);
if(fd == -1)
{
perror("open file failed");
}
}
2、函数说明
函数原型
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
参数一 路径名 参数二 操作权限 参数三 创建文件的访问权限
参数二 :O_RDWR O_RDONLY O_WRONLY 三者选其一
O_CREAT 文件不存在创建它
O_EXCL 如果同时指定了O_CREAT 文件存在则出错 判断文件是否存在
O_APPEND 每次都从文件末尾写入
O_TRUNC 若文件有内容则清除
二、文件的写入和读取
1、函数使用
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main()
{
int fd;
int n_write;
int n_read;
char *writeBuf = "xiaobian henshuai !";
char *readBuf = (char *)malloc(128);
fd = open("./file",O_RDWR|O_CREAT,0600);
if(fd == -1)
{
perror("open file failed");
}
n_write = write(fd,writeBuf,strlen(writeBuf));
if(n_write == -1)
{
perror("write file failed");
}
int size = lseek(fd,SEEK_SET,0);
if(size == -1)
{
perror("lseek failed");
}
n_read = read(fd,readBuf,n_write);
if(n_read == -1)
{
perror("read file failed");
}
printf("size is %d content is %s\n",n_read,readBuf);
close(fd);//关闭文件
return 0;
}
2、函数说明
ssize_t write(int fd, const void *buf, size_t count);
返回值:写入文件的字节大小
参数一:打开的文件描述符
参数二:缓冲区 将写入的内容存放其中
参数三:写入的大小 通常 strlen(buf)
ssize_t read(int fd, void *buf, size_t count);
返回值:读到的字节大小
参数二:缓冲区 将读到的内容存放其中
参数三:读到的字节大小
off_t lseek(int fd, off_t offset, int whence);//光标的操作函数
返回值:返回从光标到起始位置字节的个数
可以计算文件的大小:int size = lseek(fd,0,SEEK_END);
参数二:光标向后的偏移值 负数向前 正数向后
参数三:SEEK_SET 文件头
SEEK_END 文件尾
SEEK_CUR 当前位置
三、文件描述符的补充
0 标准输入流 从键盘输入
1 标准输出流 在终端输出
2 标准错误流
#include <stdio.h>
#include <unistd.h>
#include <string .h>
int main()
{
char readBuf[128];
read(0,readBuf,128);
write(1,readBuf,strlen(readBuf));
return 0;
}