簡介
在linux中,打開的的文件(可輸入輸出)標識就是一個int值,如下面的三個標準輸入輸出
STDIN_FILENO/STDOUT_FILENO/STDERR_FILENO這三個是標準輸入輸出,對應0,1,2
open(文件路徑,讀寫標識,其它不定參數)
read(文件標識,緩沖區,要讀的字節數):從文件中讀取指定的字節數到緩沖區,返回值為實際讀取的字節
write(文件標識,緩沖區,要寫的字節數):將緩沖區中指定的字節數寫入到文件中
close(文件標識):關閉文件
讀寫標識,常用的有O_RDONLY,O_WRONLY,O_RDWR,O_APPEND,O_TRUNC
lseek(文件標識,偏移量,偏移起始位置),其中偏移的起始位置有三個:
SEEK_SET:文件頭
SEEK_CUR:當前位置
SEEK_END:文件尾
例1
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
struct people{
const char name[10];
int age;
};
int main(){
int fd;
if((fd=open("./test_file",O_RDWR|O_TRUNC|O_CREAT))<0){
perror("open file error");
return -1;
}
struct people a={"zhangsan",20},b={"lisi",40},
c={"wangwu",50},d={"zhaoliu",60};
write(fd,&a,sizeof(a));
write(fd,&b,sizeof(b));
write(fd,&c,sizeof(c));
write(fd,&d,sizeof(d));
printf("input your choice:");
int num;
scanf("%d",&num);
switch(num){
case 1:
lseek(fd,0,SEEK_SET);break;
case 2:
lseek(fd,sizeof(struct people),SEEK_SET);break;
case 3:
lseek(fd,sizeof(struct people)*2,SEEK_SET);break;
default:
lseek(fd,sizeof(struct people)*3,SEEK_SET);
}
struct people test;
if(read(fd,&test,sizeof(struct people))<0){
perror("read file error");
return 1;
}
printf("your choice is %s,%d\n",test.name,test.age);
close(fd);
return 0;
例子2
dup函數用于將現在的文件標識復制一份給其它人,以達到共享文件的目的
dup2函數與dup作用一樣,但過程不一樣
如果myin、myout已經有對應的文件管道,dup2會將其關閉(如果myin/myout沒初始化會出錯),然后再復制文件標識
#include <unistd.h>
#include <stdio.h>
int main(){
int myin=dup(STDIN_FILENO);
int myout=dup(STDOUT_FILENO);
//int myin=myout=0;
//dup2(STDIN_FILENO,myin);
//dup2(STDOUT_FILENO,myout);
char buf[100]={0};
ssize_t s=read(myin,buf,100);
write(myout,buf,s);
return 0;
}