Linux文件操作示例
Linux文件操作有两种方式,c库函数和linux文件api函数,这里主要讲系统api函数,值得注意的是,文件写操作是写到缓存,不是直接写在内存文件里面,所以要更新文件或者关闭文件
linux系统文件api函数
头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
函数原型
创建
int creat(const char *filename, mode_t mode);
参数 filename 文件名字字符串形式
Mode 权限
返回 成功0 失败 -1
打开
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
参数 filename 文件名字字符串形式
flags 打开模式,读操作需要读模式,写操作需要写模式
Mode 权限
返回 文件编号
读写
int read(int fd, const void *buf, size_t length);
参数
fd 文件编号
buf 读出数据要保存数据的数组
length 要读的长度
返回 实际读出的长度
int write(int fd, const void *buf, size_t length);
参数
fd 文件编号
buf 读出数据要保存数据的数组
length 数据长度
返回 成功0 失败 -1
关闭
int close(int fd);
参数 fd 文件编号
返回 成功 0 失败-1
文件定位
int lseek(int fd, offset_t offset, int whence);
文件操作流程
读操作流程 打开文件–读文件–关闭文件
写操作流程 打开文件–写文件–关闭文件
程序示例
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
void write_file(char *s)
{
int fd;
fd = open("hello.txt", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR); //创建并打开文件
if(fd > 0)//创建成功或者打开成功
{
write(fd, s, sizeof(s));
close(fd);
}
else
{
}
}
int read_file(char *s,int len)
{
int fd,rtn_len;
fd = open("hello.txt", O_RDWR);
rtn_len = read(fd, s, len); /* 读取文件内容 */
close(fd);
return rtn_len;
}
int main()
{
char testbuf[100] = {0},len;
//写操作
write_file("hello guoguo\n");
//读操作
len = read_file(testbuf,100);
testbuf[len] = ‘/0’;
printf(“%s”, testbuf);
}