底层文件操作函数--open、close、write、read

底层文件操作函数

通过文件描述符与底层文件相关联,各函数通过文件描述符来对文件进行操作。

1、open函数

头文件:#include <unistd.h>

函数原型:int open(count char *pathname, int flags );

    int open(count char *pathname, int flags, mode_t mode )

open()函数以flags|mode 方式打开以参数pathname指向字符串为路径的文件,如成功则返回一个整型的文件描述符,read()和write()函数就可以对文件进行读写操作。

 成功:返回唯一的fd;失败:返回-1,错误记录在errorno中。

2、close函数

int close(int fd);

3、read函数

  size_t read(int fd, void *buf, size_t count);

从文件描述符fd指向的文件读取count个字节的数据,存入buf指针指向的内存单元。

4、write函数

 size_t write(int fd, const void *buf, size_t count);

将buf所在内存中的count个字节的数据写入fd指向的文件中。


eg:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include <sys/errno.h>
main()
{
int fd = 0;
int size = 0;
char s[] = "this is a test";
char buffer[50];
fd = open("test1.txt", O_WRONLY|O_CREAT|O_EXCL);
if(fd < 0){
printf("open write error,error:%d",errno);
}
write(fd, s, sizeof(s));
close(fd);
fd = open("test1.txt", O_RDONLY);
if(fd < 0)
                printf("open read error");
read(fd, buffer, sizeof(buffer));
printf("buf:%s\n",buffer);
close(fd);
}

另外对于errno的详细信息可以这样查看:

/****************************获取错误代码描述**************/
#include <string.h>
#include <errno.h>  /* for strerror */
#include <stdio.h>

int main(int argc, char ** argv)
{
  int i = 0;
  for(i = 0; i < 256; i++)
  printf("errno.%02d is: %s\n", i, strerror(i));
  return 0;
}
/*****************************************************************/


5、文件移动和重命名函数

1)remove函数

头文件:#include <stdio.h>

函数原型:remove(const char *pathname)

删除参数pathname指定的文件或目录,若是文件则调用unlink处理;若是目录,调用函数rmdir()处理。

#include <stdio.h>
main()
{
char s[]="test.txt";
int flag = 0;
flag =remove(s);
if(flag == 0){
printf("delete file successfully\n");
}else
printf("failed\n");
}

运行结果:

delete file successfully


2)rename函数

int rename(const char *oldpath, const char *newpath);

成功返回0,失败返回-1,错误记录在errno中;

#include <stdio.h>
main()
{
int flag = 0;
char old[]="out.txt";
char new[]="/root/new.txt";

//将当前目录下的out.txt文件重命名为/root目录下的new.txt文件。

flag = rename(old, new);
if(flag == 0)
printf("ok\n");
else
printf("error\n");
}


6、access函数

头文件:#include <stdio.h>

函数原型:int access(const char *pathname, int mode);

功能:检查进程是否有读写权限,参数mode有R_OK(读)、 W_OK(写)、 X_OK(执行)、 F_OK(判断文件是否存在)

成功返回0,失败返回-1,错误记录在errno中;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值