Linux文件的系统调用

Linux文件的系统调用

文件描述符

操作系统识别文件的唯一标识。当进程创建一个新文件或者打开现有文件时,系统内核向进程返回一个文件描述符。范围为0~255

三个特殊的文件描述符

前三个文件标识符在系统中规定为:
#define STDIN_FILENO 0 //标准输入文件
#define STDOUT_FILENO 1 //标准输出文件
#define STDERROR_FILENO 2 //标准错误输出文件

程序启动时会自动打开上述三个文件。

库函数与系统调用的关系

C语言的输入输出函数实际上调用的Linux内核的write、read等系统调用。read、write等函数在头文件:unisrd.h

read、write等系统调用是Linux/Unix的上,只有在Linux/Unix平台上才有效。

基本系统调用

  1. create() // 创建文件
  2. open() //打开文件
  3. read() //读文件
  4. write() //写文件
  5. close() //关闭文件
  6. lseek() //移动文件指针
  7. chmod() //改变文件权限
  8. chown() //改变文件所有者

1.创建文件 create

#include<sys/types.h>
#include<sys/stat.h>    //包含着权限宏定义的头文件
#include<fcntl.h>
int creat(const char *pathname, mode_t mode);

pathname:要创建文件的路径(绝对路径/相对路径)
mode:要创建文件的权限
返回值:若调用成功,则返回文件描述符;否则返回-1

mode定义在头文件include/linux/stat.h中:

2.打开文件 open

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

pathname: 文件路径(绝对路径/相对路径)
flags: 打开方式
mode:权限。可选参数,只在创建新文件时有效
返回值:若调用成功,则返回文件描述符;否则返回-1

参数flag说明:

3.关闭文件 close

#include<unistd.h>
int close(int fd);

fd: 要关闭文件的描述符
返回值:若调用成功,则返回0;否则返回-1

4.读文件 read

#include<unistd.h>
ssize_t read(int fd, const void *buf, size_t count);

fd: 文件描述符
buf:缓冲区指针,用于缓存从文件中读取的数据
count:要读取的字节数
返回值:执行成功,返回读取到的真正的字节数;失败则返回-1。

例子,读入所有字节:

ssize_t ret;
while(len != 0 && (ret = read(fd, buf, len)) != 0)
{
    if(ret == -1)
    {
        if(errno == EINTR)
            continue;
        perror("read");
        break;
    }
    len -= ret;
    buf += ret;
}

5.写文件 write

#include<unistd.h>
ssize_t write(int fd, const void *buf, size_t count);

fd: 文件描述符
buf:缓冲区指针,用于缓存准备写入文件的数据
count:要写入的字节数
返回值:执行成功,返回写入的真正的字节数;失败则返回-1。

6.移动文件指针 lseek

#include<unistd.h>
#include<sys/types.h>
off_t lseek(int fd, off_t offest, int whence);

fd: 文件描述符
offset:文件指针相对于whence的偏移量
whence:偏移的基准位置
返回值:返回实际相对于文件开头的偏移量

7.改变文件权限 chmod

#include<sys/types.h>
#include<unistd.h>
int chmod(const char *path, mode_t mode);

path: 文件路径名(绝对路径/相对路径)
mode:权限组合
返回值:调用成功返回0;否则返回-1

8.改变文件所有者 chown

#include<sys/types.h>
#include<unistd.h>
int chown(const char *path, uid_t owner, gid_t group);

path: 文件路径名
owner:变更的UID
group:变更的GID
返回值:调用成功返回0;否则返回-1

猜你喜欢

转载自blog.csdn.net/neverwa/article/details/79983568