linux 文件I/O教程(1) 一,文件描述符 对内核而言,所以打开的文件都通过文件描述符引用。每个进程都有一些与之关联的文件描述符。文件描述符是一个非负整数。当打开一个现有文件或创建一个新文件时,内核向进程返回一个文件描述符。当读或写一个文件时,使用open或creat返回的文件描述符标识该文件,将其作为参数传送给read和write。 一般有三个以及打开的文件描述符,他们是:
复制代码代码如下: #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> int open(const char *pathname, int flags); int open(const char *pathname, int flags,mode_t mode);
复制代码代码如下: SEEK_SET: The offset is set to offset bytes. SEEK_CUR:The offset is set to its current locationplus offset bytes. SEEK_END:The offset is set to the size of the fileplus offset bytes.
复制代码代码如下: #include<unistd.h> //<unistd.h>必须最早出现,因为它可能会影响到其他头文件。#include<stdio.h> #include<fcntl.h> #include<string.h> #include<errno.h> int main() { char* filename = ".//file"; char buf[100]; char buf1[5]; int fd;
printf("open a file to write
"); if((fd = open(filename,O_RDWR|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH ))==-1) { perror("cannot open file
"); return 1; } printf("open file successfully!
"); printf("input a string:"); gets(buf); //write intofile if(write(fd,buf,strlen(buf)) !=strlen(buf)) { perror("cannot write intofile
"); return 1; } close(fd);
printf("open file to read.
"); if((fd=open(filename,O_RDONLY)) == -1) { perror("cannot open thefile.
"); return 1; } if(lseek(fd,3,SEEK_SET) == -1) { perror("lseek erroe
"); return 1; } //read from the file if(read(fd,buf1,4)==-1) { perror("read error.
"); return 1; } printf("read from file is%s
",buf1); close(fd);
return 0; }
执行与输出结果:
复制代码代码如下: root@jb51:~$gcc -o io io.c root@jb51:~$./io open a file towrite open filesuccessfully! input a string:akxivbaslzkncxcasbxbwwvaidxbd open file toread. read from fileis ivba