第24节:open 打开文件操作
驱动设备的节点
ls /dev/leds
编写运行编译open例程
1)首先看一下帮助文档内容
topeet@ubuntu:~$ man 2 open
2)open.c创建
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
main(){
int fd;
char *leds = "/dev/leds";
char *test1 = "/bin/test1";
char *test2 = "/bin/test2";
if((fd = open(leds,O_RDWR|O_NOCTTY|O_NDELAY))<0){
printf("open %s failed!\n",leds);
}
printf("%s fd is %d\n",leds,fd);
if((fd = open(test1,O_RDWR,0777))<0){
printf("open %s failed!\n",test1);
}
printf("%s fd is %d\n",test1,fd);
if((fd = open(test2,O_RDWR|O_CREAT,0777))<0){
printf("open %s failed!\n",test2);
}
printf("%s fd is %d\n",test2,fd);
}
3)进行文件编译
root@ubuntu:/home/linuxsystemcode/open# arm-none-linux-gnueabi-gcc -o open open.c
4)将文件拷贝到TF卡,看如下超级终端信息并挂载TF卡:
[ 3245.885451] mmc_sd_detect(mmc1): Unable to re-detect card (-123)
[ 3245.890126] mmc1: card 0001 removed
[ 3383.120205] *******mmc1: inserted!!!!!******
[ 3383.285835] mmc1: new high speed SDHC card at address 0001
[ 3383.305216] mmcblk1: mmc1:0001 00000 7.44 GiB
[ 3383.315345] mmcblk1: p1
[root@iTOP-4412]# mount /dev/mmcblk1p1 /mnt
[root@iTOP-4412]# df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/root 302360 14540 287820 5% /
tmpfs 307092 0 307092 0% /dev/shm
/dev/mmcblk1p1 7787604 660 7786944 0% /mnt
5)查看TF卡内容,并执行open文件
[root@iTOP-4412]# ./open
[ 38.863795] LEDS_CTL DEBUG:Device Opened Success!
[ 38.867350] LEDS_CTL DEBUG:Device Closed Success!
/dev/leds fd is 3
open /bin/test1 failed!
/bin/test1 fd is -1
/bin/test2 fd is 4
驱动设备的节点
ls /dev/leds
编写运行编译open例程
1)首先看一下帮助文档内容
topeet@ubuntu:~$ man 2 open
2)open.c创建
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
main(){
int fd;
char *leds = "/dev/leds";
char *test1 = "/bin/test1";
char *test2 = "/bin/test2";
if((fd = open(leds,O_RDWR|O_NOCTTY|O_NDELAY))<0){
printf("open %s failed!\n",leds);
}
printf("%s fd is %d\n",leds,fd);
if((fd = open(test1,O_RDWR,0777))<0){
printf("open %s failed!\n",test1);
}
printf("%s fd is %d\n",test1,fd);
if((fd = open(test2,O_RDWR|O_CREAT,0777))<0){
printf("open %s failed!\n",test2);
}
printf("%s fd is %d\n",test2,fd);
}
3)进行文件编译
root@ubuntu:/home/linuxsystemcode/open# arm-none-linux-gnueabi-gcc -o open open.c
4)将文件拷贝到TF卡,看如下超级终端信息并挂载TF卡:
[ 3245.885451] mmc_sd_detect(mmc1): Unable to re-detect card (-123)
[ 3245.890126] mmc1: card 0001 removed
[ 3383.120205] *******mmc1: inserted!!!!!******
[ 3383.285835] mmc1: new high speed SDHC card at address 0001
[ 3383.305216] mmcblk1: mmc1:0001 00000 7.44 GiB
[ 3383.315345] mmcblk1: p1
[root@iTOP-4412]# mount /dev/mmcblk1p1 /mnt
[root@iTOP-4412]# df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/root 302360 14540 287820 5% /
tmpfs 307092 0 307092 0% /dev/shm
/dev/mmcblk1p1 7787604 660 7786944 0% /mnt
5)查看TF卡内容,并执行open文件
[root@iTOP-4412]# ./open
[ 38.863795] LEDS_CTL DEBUG:Device Opened Success!
[ 38.867350] LEDS_CTL DEBUG:Device Closed Success!
/dev/leds fd is 3
open /bin/test1 failed!
/bin/test1 fd is -1
/bin/test2 fd is 4