关于linux文件操作一些函数的学习

一.什么是系统调用,为什么要系统调用

  要说这个问题,就得先说说我们开始学的那些标准库函数,比如fopen,fclose,fread等等,这些函数实际上是由open,close,read等系统调用完成的。
  系统调用是内核提供给我们的接口,让程序能够与硬件交互,系统调用相当于提供了一个中间层,它更加的安全,基本操作命令是提供给用户使用的,而系统调用是提供给程序员使用的,系统调用可以用于系统空间,而标准函数无法用于内核空间,所以系统调用是相当必要的。标准库函数可以用来开发可移植性程序,而系统调用由于是内核提供的,故不能用于移植程序的开发。

二.几种常见的函数使用方法

1.chmod/fchmod函数
原型如下:

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

mode有几种常见形式可以总结几个通式
S_I*xxx
注:*为R即为可读,W即为可写,X即为可执行。xxx为USR即为文件所有者,为GRP即为用户组,OTH即为其他用户

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

flags表示打开文件的方式
O_RDONLY:以只读方式打开文件
O_WRONLY:以只写方式打开文件
O_RDWR:一可读可写的方式打开文件   注意:这三种打开方式互斥

mode与chmod函数的mode相同

3.creat函数
原型如下:

#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
int creat(const char *pathname,int flags,mode_t mode);

注意:open和creat成功调用时返回一个文件描述符

4.read函数

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

从文件描述符fd所指向的文件中读取count个字节的数据到buf所指向的缓存中。

5.stat/fstat/lstat函数

#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int stat(const char *file_name,struct stat *buf);
int fstat(int filedes,struct stat *buf);
int lstat(const char*file_name,struct stat *buf);

执行成功返回0,错误时返回-1,错误代码存入errno中

指定文件名的状态信息保存在参数struct stat *buf中;

6.opendir/readdir/closedir函数

opendir函数
#include<sys/types.h>
#include<dirent.h>
DIR *opendir(const char*name);
打开指定的名的目录,返回DIR*形态的目录流,类似于文件操作中的文件描述符

readdir函数
#include<sys/types.h>
#include<dirent.h>
struct dirent *readdir(DIR *dir);
返回一个struct dirent结构的指针

closedir函数
#include<sys/types.h>
#include<dirent.h>
int closedir(DIR *dir);
关闭参数dir指向的目录,执行成功返回0,有错误发生时返回-1;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值