文件IO

来源:互联网 发布:夜恋秀场破解软件 编辑:程序博客网 时间:2024/04/27 23:25

1、文件描述符

    对于内核而言,所有打开的文件都通过文件描述符引用,文件描述符是一个非负整数


2、open函数

    调用open函数可以打开或者创建一个文件

    #include <fcntl.h>

    int open(const char *pathname, int oflag, ...);  /*成功则返回文件描述符,否则返回-1*/

    *1、pathname:表示的是要打开或者创建文件的名字。

    *2、oflag:说明此函数打开的多个选项

            O_RDONLY    只读打开。

            O_WRONLY   只写打开。

            O_RDWR        读、写打开。

    上面的三个常量中必须指定一个且只能指定一个。下面是可选的:

     O_APPEND,O_CREAT,O_EXCL,O_TRUNC,O_NOCTTY,O_NONBLOCK,O_DSYNC,O_RSYNC,O_SYNC。


3、create函数

    调用create函数创建一个新文件。

    #include <fcntl.h>

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

    注意,此函数等效于:open(pathname, O_WRONLY | O_CREAT | O_TRUNC, mode);


4、close函数

    可调用close函数关闭一个打开的文件:

    #include <unistd.h>

    int close(int filedes);

    当一个进程终止时,内核会自动关闭它所有打开的文件。


5、lseek函数

    每一个打开的文件都有一个与其相关联的“当前文件偏移量 current file offset”, 它通常是一个非负整数,除非指定O_APPEND选项,否则该偏移量置0。

    #include <unistd.h>

    off_t lseek(int filedes, off_t offset, int whence);/*成功,返回新的文件偏移量,出错返回-1*/

    *1、offset,为偏移量

    *2、whence 可以为SEEK_SET, SEEK_CUR, SEEK_END

    eg:可以用来确定整个文件的大小

    #include <....h>

    int sizeFile;

    sizeFile = lseek(fd, 0, SEEK_END);


6、read函数

    调用read函数从打开文件中读取数据。

    #include <unistd.h>

    ssize_t read(int filedes, void *buf, size_t nbytes);/*成功,返回读到的字节数,到尾则返回0,出错返回-1*/


7、write函数

    调用write函数向打开阿文件写数据。

    #include <unistd.h>

    ssize_t wirite (int filedes, const void *buf, size_t nbytes);/*成功,返回已写的字节数,出错返回-1*/




原创粉丝点击