標籤:io ar os 使用 sp for on 檔案 bs
在看韋東山視頻linux驅動方面有一些吃力,究其原因,雖然接觸過linux應用程式編程,但是沒有深入去理解,相關函數用法不清楚,正好看到國嵌視頻對這一方面講的比較透徹,
所以把學習過程記錄下來,也作為linux應用程式開發的一個系列吧!
檔案編程有兩種方式,一是系統調用方式,二是庫函數調用。
前者依賴特定的平台,後者不依賴平台。
系統調用:建立
int creat(const char *filename,mode_t mode);
filename:要建立的檔案名稱
mode:建立模式
S_IRUSR->1
S_IWUSR->2
S_IWXUSR->4
S_IRWXU->7
系統調用舉例:
#include <stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<fcntl.h>
void create_file(char *filename)
{
if(creat(fileanme.,0755)<0)
{
printf("create file %s is failuer!\n",filename);
}
else
{
printf("create file %s is success!\n",filename)
}
}
int main(int argc,char *argv[])
{
int i;
if(argc<2)
{
perror("you haven‘t input the filename ,please try agin!\n");
exit(EXIT_FAILUER);
}
for(i=1;i<argc;i++)
{
create_file(argv[i]);
}
exit(EXIT_SUCCESS);
}
檔案描述:檔案描述符 範圍0-OPEN-MAX。早期允許每個進程開啟20個。現在有些增長到1024個。
系統調用-開啟
int open(const char*pathname,int flags);
int open(const cahr*pathname,int falgs,mode_t mode);
flags:開啟標誌
O_RDONLY
O_WRONLY
O_RDWR
O_APPEBD:追加方式開啟
O_CREAT:必須使用函數 int open(const cahr*pathname,int falgs,mode_t mode);
O_NOBLOCK:非阻塞方式開啟
舉例:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int main(int argc,char *argv[])
{
int fd;
if(argc<2)
{
puts("please input yhe open file pathname!\n");
exit(1);
}
if((fd=open(argv[1],O_CREAT|)CREAT_ORDWR,0755)<0)
{
perror("open file failuer!\n");
exit(1);
}
else
{
printf("open file %d is success!\n",fd);
}
close(fd);
exit(0);
}
檔案關閉:
int close(fd);
系統調用-讀
int read(int fd ,const void *buf,size_t length);
從檔案描述符fd所指定的檔案中讀取length個位元組到buf所指定的緩衝區,返回實際讀取的位元組數。
寫:int write(int fd ,const void *buf,size_t length);
定位:
int lseek(int fd,offset_t offset,int whence);
將檔案讀寫指標相對於whence移動offset個位元組。操作成功時,返迴文件指標相對於檔案頭的位置。
whence:
SEEK_SET:相對檔案開頭
SEEK_CUR:相對檔案讀寫指標的當前位置
SEEK_END:相對檔案末尾
計算檔案長度:
系統調用-訪問判斷:
int access(const char*pathname,int mode);
mode:要判斷的存取權限。可以取以下值或他們的組合
R_OK
W_OK
X_OK
F_OK:檔案存在
成功返回0,否則條件不符合則返回1。
舉例:
#include<unistd.h>
int main()
{
if(access("/etc/passwd",R_OK)==0)
printf("/etc/passwd can be read!"\n);
}
linux應用程式開發-檔案編程-系統調用方式