unix/Linux低級(jí)IO函數(shù)的用法
unix/Linux 低級(jí)IO函數(shù)的用法,必須掌握寫module ,必要的應(yīng)用編程知識(shí)是應(yīng)該要有的, 否則 ,怎么寫應(yīng)用程序來(lái)測(cè)試你的module或者driver呢?
而且最主要的是 , 了解上層調(diào)用的接口, 你就明白了上層的開(kāi)發(fā)者需要什么, 自己才好實(shí)現(xiàn)什么。
把手里的看書(shū)的事情都放下, 先把 Unix環(huán)境高級(jí)編程這本書(shū) 的第三章 徹底搞熟它。
內(nèi)容包括:
open() ,尤其是各種常見(jiàn)的參數(shù),到底是什么意思, 比如常用創(chuàng)建一個(gè)空文件: fd = open("/tmp/xx.txt",O_RDWR | O_CREAT | O_TRUNC);
讀一個(gè)文件,fd = open("/dev/hello",O_RDONLY );
如果就是要寫一個(gè)既有的文件,fd = open("/dev/hello",O_WRONLY );
具體的參數(shù): man 2 open
read(),
write()
ioctl() ,這個(gè)最重要。
lseek() , 文件指針移動(dòng)
#p#比如下面的例子:
就是簡(jiǎn)單的讀一個(gè)文件:
#include
#include
#include
#include
int main(int argc,char **argv)
{
int fd = 0;
int pid = 0;
char buffer[20] = {'\0'};
char *read_buffer[20] = {'\0'};
//fd = open("/dev/hello",O_RDWR | O_CREAT | O_TRUNC);
fd = open("/dev/hello",O_RDONLY ); //| O_NONBLOCK);
printf("fd=%d\n",fd);
if(fd < 0) {
perror("/dev/hello");
return -1;
}
read(fd,read_buffer,sizeof(read_buffer)-1);
printf("read_buffer=%s\n",read_buffer);
close(fd);
return 0;
}
下面這個(gè)就是簡(jiǎn)單的寫一個(gè)文件 ,
#include
#include
#include
#include
int main(int argc,char **argv)
{
int fd = 0;
int pid = 0;
char buffer[20] = {'\0'};
char write_buffer[20] = {'\0'};
strcpy(write_buffer,"zhanglinbao");
fd = open("/dev/hello",O_RDWR | O_CREAT | O_TRUNC);
//fd = open("/dev/hello",O_RDONLY);
printf("fd=%d\n",fd);
if(fd < 0) {
perror("/dev/hello");
return -1;
}
write(fd,write_buffer,sizeof(write_buffer)-1);
close(fd);
return 0;
}
【編輯推薦】