在Linux中所有的设备都是作为文件存在的,因此要操作对应的外设需要先学习文件操作
基本的文件操作会用到open/read/write/lseek/close这几个方法
- int open (const char *__path, int __oflag, .../* mode_t mode */)
需要#include <fcntl.h>,用来打开文件,如果打开成功会返回一个非负的值作为文件描述符,之后的read write lseek close都要用到这个值
char *__path:文件路径
int __oflag:打开文件方式,常用的有O_RDONLY(只读), O_WRONLY(只写 ),O_RDWR(读写),O_CREAT (创建),O_TRUNC(截断)
mode_t mode:当__oflag有O_CREAT时用于指定新创建的文件的权限
- ssize_t read(int fd, void buf[.count], size_t count)
需要#include <unistd.h>,用来从打开的文件中读出指定长度的数据,读取成功会返回实际读取的数据长度
int fd:文件描述符
void buf[.count]:用于接收读取数据
size_t count:需要读取的长度
- ssize_t write(int fd, const void buf[.count], size_t count)
需要#include <unistd.h>,用来向打开的文件中写入指定长度的数据,写入成功后返回实际写入的数据长度
int fd:文件描述符
void buf[.count]:要写入的数据
size_t count:写入的数据长度
- off_t lseek(int fd, off_t offset, int whence)
需要#include <unistd.h>,用来重新定位读取写入的位置
int fd:文件描述符
off_t offset:偏移量
int whence:偏移参考点,SEEK_SET(相对于文件开始的位置),SEEK_CUR(相对于当前的位置),SEEK_END(相对于文件末尾)
需要#include <unistd.h>,用来关闭打开的文件
int fd:文件描述符
接下来写个简单的程序来演示一下
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <stdio.h>
- #include <errno.h>
- #include <string.h>
- #include <unistd.h>
- #include <stdlib.h>
- #define BUF_SIZE 1024
- //file_test 1.txt 4 abcdefgh
- int main(int argc,char **argv)
- {
- int fd,len;
- char buf[BUF_SIZE];
- memset(buf,0,BUF_SIZE);
- if(argc < 2)
- {
- printf("need file path\n");
- return -1;
- }
- fd = open(argv[1],O_RDWR|O_CREAT,S_IRUSR|S_IWUSR);
- if (fd < 0)
- {
- perror("open file error");
- }
- else
- {
- printf("open file: %s\n",argv[1]);
- do
- {
- len = read(fd,buf,BUF_SIZE);
- if(len > 0)
- {
- printf("read %d bytes\n",len);
- printf("%s\n",buf);
- }
- }while (len > 0);
- if(argc == 4)
- {
- printf("write at %d\n",atoi(argv[2]));
- lseek(fd,atoi(argv[2]),SEEK_SET);
- write(fd,argv[3],strlen(argv[3]));
- }
- }
- close(fd);
- printf("\n");
- return 0;
- }
这段代码可以在Ubuntu上用GCC编译运行和在Arm开发板上的效果是一样的
|