日期:2014-05-16  浏览次数:20635 次

Linux学习笔记七:文件操作(系统调用方式)

首先需要问的是Linux中有没有像java doc 那样的API查看文档呢?

结果是肯定的,查看方法有二:  

1.在命令行用man  XXX  查看即可 ,按q退出。如查看open()函数,man open 即可,按空格键查看下一页;

2.也可登录Linux man-pages主页查看:http://man7.org/linux/man-pages/dir_all_alphabetic.html,在这里我们可以查看到所有的API接口;

系统调用方式的文件操作主要用到的函数有如下几个:

1.open   SYNOPSIS         top

       #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);

       int creat(const char *pathname, mode_t mode);

函数返回的是一个非负整数作为文件描述符,而该描述符的范围是0-OPEN_MAX,该描述符用于下面将要介绍的read,write等函数中作为输入参数,所以一般都要用变量把文件描述符存储起来。

pathname是要打开或创建的文件名,flags参数用于指定文件的访问方式且只能为:O_RDONLY,O_WRONLY, O_RDWR中的一个或多个(必须),当然还可以或上别的参数如O_APPEND等(可选),具体查看文档。

2.creat

#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);

       int creat(const char *pathname, mode_t mode);

3.close

  #include <unistd.h>

       int close(int fd);
fd是所要关闭的文件描述符.

4.lseek

SYNOPSIS         top

       #include <sys/types.h>
       #include <unistd.h>

       off_t lseek(int fd, off_t offset, int whence);
若成功则返回新的文件偏移量,出错则返回-1; offset 与whence相关,其中whence可取值为:
       SEEK_SET         文本开始处
              The offset is set to offset bytes. 

       SEEK_CUR         当前值