SylixOS字符设备驱动开发(一)
SylixOS文件基本操作
文件的基本操作包括打开文件、关闭文件、读文件和写文件。打开文件通过调用open函数来实现:
int fd;
fd = open("demo.txt", O_RDWR | O_CREAT);
if (fd < 0) {
printf("open file fail.\r\n");
return -1;
}
O_RDWR表示以可读可写的方式打开文件,O_CREAT表示如果文件不存在则创建新文件。文件打开成功后会返回一个文件描述符,后续对文件的操作都是基于这个文件描述符来进行的。关闭文件通过调用close函数来实现:
close(fd);
写文件通过write函数来实现:
ssize_t size;
char buffer_w[10] = {'1', '2', '3', '4'};
size = write(fd, buffer_w, 4);
if (size < 0) {
printf("write file fail.\r\n");
return -1;
}
write的返回值表示写成功的字节数。读文件通过read函数来实现:
char buffer_r[10] = {0,};
size = read(fd, buffer_r, size);
if (size < 0) {
printf("read file fail.\r\n");
return -1;
} else if (!size) {
printf("read file end.\r\n");
}
read的返回值表示读成功的字节数,为0表示未读到数据或者读到文件末尾。通过一个demo来测试文件的基本操作:
#include <stdio.h>
int main (int argc, char **argv)
{
int fd;
ssize_t size;
char buffer_w[10] = {'1', '2', '3', '4'};
char buffer_r[10] = {0,};
fd = open("demo.txt", O_RDWR | O_CREAT);
if (fd < 0) {
printf("open file fail.\r\n");
return -1;
}
size = write(fd, buffer_w, 4);
if (size < 0) {
printf("write file fail.\r\n");
return -1;
}
close(fd);
fd = open("demo.txt", O_RDWR | O_CREAT);
if (fd < 0) {
printf("open file fail2.\r\n");
return -1;
}
size = read(fd, buffer_r, size);
if (size < 0) {
printf("read file fail.\r\n");
return -1;
} else if (!size) {
printf("read file end.\r\n");
}
printf("read : %s\r\n", buffer_r);
close(fd);
return (0);
}
测试结果:
[root@sylixos:/apps/app_demo1]# ./app_demo1
read : 1234
[root@sylixos:/apps/app_demo1]#