刚开始学Linux,首先学习文件的读取。文件的读取我们不采用ASNI标准的头文件,采用POSIX标准,按照这个规范能更好地操作驱动。首先我们了解最基本的几个头文件。
#inlucde <sys/types.h> //基本的系统数据类型
#include<sys/stat.h> //文件状态
#include <fcntl.h> //文件控制定义
open();// 函数,打开文件
creat();// 函数,创建文件
close();// 函数,关闭文件
#include <unistd.h> //文件操作头文件
read();//读取文件
write();//写入文件
lseek() ;// 文件定位
fcntl() ;// 修改文件属性
?
#include <errno.h> 记录文件最后一次的错误代码c语言
extern int errno;
?
下面我们写一个例子,如何对文件进行创建,读取和修改,如果需要进一步的操作,需要查阅相关的手册,资料
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
?
extern int errno;
?
int main(void)
{
int fd;
char buf[64]=”Hello World,CROSS THE GREAT WALL!”;
off_t cur_pos;
fd=open(“./my.txt”,O_CREAT|O_RDWR|O_EXCL,S_IRWXU);//创建my.txt
if(-1==fd)
{
switch(errno)
{
case EEXIST://如果存在,那就就提示存在
printf(“file exist”);
break;
default://出错,那就提示找不到
printf(“can not find”);
break;
}
?
}
?
write(fd,buf,strlen(buf));//写入文件
?
cur_pos=lseek(fd,0,SEEK_CUR);//获取当前光标的位置
printf(“offset cursor %d\n”,cur_pos);
strcpy(buf,”new”);
write(fd,buf,strlen(buf));//在末尾继续插入字符
close(fd);//关闭文件
return 0;
}
这样我们就完成了最基本的文件操作,并且我们不是用fstream之类的头文件。然后我们开始操作leds,led相当于一个文件,我们对其进行读写,从而改变它的状态。但是我们采用的是ioctl命令,该命令是设备驱动程序对IO通道管理的函数。
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>//io口操作头文件
#include <sys/wait.h>//sleep所需要的头文件,只有这样才能使用延时操作
int main(void)
{
int fd;
char leds[]=”/dev/leds”;//打开设备leds
if (-1==(fd=open(leds,O_RDWR|O_NOCTTY|O_NDELAY)))
{
printf(“leds open fail”);
return 0;
}
ioctl(fd,1,0);//操作设备
ioctl(fd,0,1);
printf(“open success”);
?
sleep(3);//延时3s
return 0;
}
我们通过进行学习文件的操作,Led简单操作入门,然后明天继续开始下一步的学习。
http://www.xncae.com/html/86.html
心中有愿望一定要去闯,努力实现最初的梦想,