#include <sys/types.h> //定义了一些常用数据类型,比如size_t
#include <fcntl.h> //定义了open、creat等函数,以及表示文件权限的宏定义
#include <unistd.h> //定义了read、write、close、lseek等函数
#include <errno.h> //与全局变量errno相关的定义
#include <sys/ioctl.h> //定义了ioctl函数
#include <stdio.h>
int open_file(char *filename,char *write_dat)
{
int fd = -1;
int res = 0;
char read_buf[128] = {0};
/* 写入文件操作示例 */
//1. 打开文件
fd = open(filename, O_RDWR | O_CREAT, 0664);
if(fd < 0)
{
printf("%s file open fail,errno = %d.\r\n", filename, errno);
return -1;
}
//2. 读取内容
res = write(fd, write_dat, sizeof(write_dat));
if(res < 0)
{
printf("write dat fail,errno = %d.\r\n", errno);
return -1;
}
else
{
printf("write %d bytes:%s\r\n", res, write_dat);
}
//3. 关闭文件
close(fd);
/* 读取文件数据示例 */
//1. 打开文件
fd = open(filename, O_RDONLY);
if(fd < 0)
{
printf("%s file open fail,errno = %d.\r\n", filename, errno);
return -1;
}
//2. 写入内容
res = read(fd, read_buf, sizeof(read_buf));
if(res < 0)
{
printf("read dat fail,errno = %d.\r\n", errno);
return -1;
}
else
{
printf("read %d bytes:%s\r\n", res, read_buf);
}
//3. 关闭文件
close(fd);
}
int main(void)
{
char main_filename[] = "test.txt";
char main_write_dat[] = "Hello World!";
open_file(&main_filename[],&main_write_dat[]);
return 0;
}