LinuxC编程实战之文件操作

1.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);
调用成功返回一个文件描述符,失败返回-1.

2.creat函数

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int open(const char *pathname, mode_t mode);
调用成功返回一个文件描述符,失败返回-1.
Note:creat只能以只写的方式打开创建的文件,creat无法创建设备文件,设备文件的创建要使用mknod函数.

3.close函数

#include <unistd.h>
int close(int fd);
调用成功返回0,失败返回-1.
Note:close函数调用成功时并不保证数据能全部写回硬盘.

4.lseek函数

#include <sys/types.h>
#include <unistd.h>
off_t lseek(int fildes, off_t offset, int whence);
调用成功返回新的偏移量,失败返回-1.
Note:打开文件时通常读写位置是指向文件开头,若是追加方式打开文件,读写位置会指向文件尾.

5.stat函数

#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.

6.utime函数

#include <sys/types.h>
#include <utime.h>
int utime(const char *filename, struct utimebuf *buf);

#include <sys/time.h>
int utimes(char *filename,struct timeval *tvp);
调用成功返回0,失败返回-1.
Note:utime系统调用会把由第一个参数filename指定的文件的存取时间改为第二个参数buf的actime域,把修改时间改为第二个参数buf的modtime域,如果buf是一个空指针,则存取时间和修改时间都改为当前时间.

7.getcwd函数

#include <unistd.h>
char *getcwd(char *buf, size_t size);
char *get_current_dir_name(void);
char *getwd(char *buf);
成功则将结果复制到参数buf所指的内存空间,或是返回自动配置的字符串指针,失败返回NULL.
Note:getcwd会将当前的工作目录绝对路径复制到参数buf所指的内存空间,buf所指的内存空间要足够大.

8.opendir函数

#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
成功返回DIR*型态的目录流,失败则返回NULL.

9.readdir函数

#include <sys/types.h>
#include <dirent.h>
struct dirent *readdir(DIR *dir);
struct dirent
{
    long d_ino;   //目录i节点编号
    off_t d_off;  //目录开头至此目录进入点的位移
    unsigned short d_reclen;  //文件名的长度
    char d_name [NAME_MAX+1]; //以NULL结尾的文件名
};
函数执行成功返回该目录下一个文件信息,第一次调用返回第一个文件信息,第二次调用返回第二个,以此类推;
函数调用如有错误发生或读取到目录文件尾,则返回NULL.

10.closedir函数

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值