一.创建/打开文件
函数原形:
#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 可多选
flags 常用选项:
O_RDONLY 只读方式打开
O_WRONLY 只写方式打开
O_RDWR 读写方式打开
O_CREAT 如果文件不存在就创建
O_APPEND 每次写都追加到文件尾
O_EXCL 如果同时指定了O_CREAT,文件已存在则报错(可用来判断文件是否存在)
O_TRUNC 如果文件存在,且为只写或读写方式成功打开,则将其长度截断为0。(可用于清空文件内容)
@mode 文件的权限位(只有在flags中有O_CREAT选项时文件权限才有效)
S_IRWXU 允许 文件的属主读 , 写和执行文件
S_IRUSR (S_IREAD) 允许文件的属主读文件
S_IWUSR (S_IWRITE) 允许文件的属主写文件
S_IXUSR (S_IEXEC) 允许文件的属主执行文件
S_IRWXG 允许文件 所在的分组读 , 写和执行文件
S_IRGRP 允许文件所在的分组读文件
S_IWGRP 允许文件所在的分组写文件
S_IXGRP 允许文件所在的分组 执行文件
S_IRWXO 允许其他用户读 , 写和执行文件
S_IROTH 允许其他用户读 文件
S_IWOTH 允许其他用户写 文件
S_IXOTH 允许其他用户执行 文件
返回值:成功返回文件描述符,失败返回 -1
二.关闭文件
函数原形:
#include <unistd.h>
int close(int fd);
参数:fd 文件描述符
返回值:成功返回 0,失败返回 -1
三.文件偏移量
函数原形:
#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fd, off_t offset, int whence);
参数:offset与whence有关
当whence是SEEK_SET,则将该文件偏移量设置为距离文件开始出offset个字节处
当whence是SEEK_CUR,则将该文件偏移量设置为其当前值加offset,offset可为正或负
当whence是SEEK_END,则将该文件偏移量设置为文件长度加offset,offset可为正或负(文件偏移量可以大于文件长度)
返回值:成功返回新的文件偏移量,失败返回 -1
备注:管道 FIFO 网络套接字 描述符不可设置偏移量
四.写文件
函数原形:
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
参数:fd 文件描述符 ,buf 缓冲区,count 读去的大小不超过SSIZE_MAX
返回值:成功返回写的字节数,失败返回 -1
五.读文件
函数原形:
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
参数:fd 文件描述符 ,buf 缓冲区,count 读去的大小不超过SSIZE_MAX
返回值:读到的字节数,如果读到文件尾返回0,出错返回 -1
示例代码:
/*************************************************************************
> File Name: base-file.c
> Author:
> Mail:
> Created Time: 2017年03月08日 星期三 14时09分46秒
************************************************************************/
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
/* 错误处理 */
void err_exit(const char *s)
{
perror(s);
exit(EXIT_FAILURE);
}
int main(void)
{
int fd; // 文件描述符
char rdbuf[10]; // 读缓冲区
char wrbuf[1024]; // 写缓冲区
/* 只写方式打开文件,如果文件不存在创建文件,文件权限644 */
if ((fd = open("test", O_WRONLY|O_APPEND|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH)) == -1)
err_exit("open");
/* 写文件 */
strcpy(wrbuf, "abc1234854defgABCDEFG123456gg");
if (write(fd, wrbuf, strlen(wrbuf)) == -1)
err_exit("write");
/* 关闭文件 */
close(fd);
/* 只读方式打开文件 */
if ((fd = open("test", O_RDONLY)) == -1)
err_exit("open");
/* 读文件 */
int size = 1, i = 0;
while (1)
{
size = read(fd, rdbuf, 10);
if (size == 0)
break;
if (size == -1)
err_exit("read");
for (i=0; i<size; i++)
{
printf("%c", rdbuf[i]);
}
}
printf("\n");
/* 关闭文件 */
close(fd);
return 0;
}