32.Linux应用层开发--文件IO

 

件IO和标准IO功能是相同的,一些细节上会有一些不同之处。

一.文件IO基本介绍:

1.文件IO:posix(可移植操作系统接口)定义的一组函数

2.不提供缓冲机制,每次读写操作都引起系统调用

3.核心概念是文件描述符,访问各种类型文件

4.Linux下, 标准IO基于文件IO实现

5.文件IO和标准IO操作的区别

32.Linux应用层开发--文件IO

 

二.文件IO的打开和关闭

1.

#include <fcntl.h>

int  open(const char *path, int oflag, …)

成功时返回文件描述符;出错时返回EOF

打开文件时使用两个参数

创建文件时第三个参数指定新文件的权限

只能打开设备文件

32.Linux应用层开发--文件IO

 

O_RONLY | O_EXCL        r

O_RDWR |O_EXCL           r+

O_CREAT | O_TRUNC | O_WRONLY       w

O_CREAT | O_TRUNC | O_RDWR            w+

O_CREAT | O_APPEND | O_WRONLY     a

O_CREAT | O_APPEND | O_RDWR         a+

 

例:if ((fd  = open(“1.txt”, O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)

2.

 #include  <unistd.h>

 int  close(int fd);

成功时返回0;出错时返回EOF

程序结束时自动关闭所有打开的文件

文件关闭后,文件描述符不再代表文件

 

三.读写文件,定位文件

1.

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

成功时返回实际读取的字节数;出错时返回EOF

读到文件末尾时返回0

buf是接收数据的缓冲区

count不应超过buf大小

2.

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

成功时返回实际写入的字节数;出错时返回EOF

buf是发送数据的缓冲区

count不应超过buf大小

3.

 off_t  lseek(int fd, off_t offset, intt whence);

成功时返回当前的文件读写位置;出错时返回EOF

参数offset和参数whence同fseek完全一样

 

四.文件属性,目录操作

1.打开一个目录文件

 #include  <dirent.h>

 DIR  *opendir(const char *name);

DIR是用来描述一个打开的目录文件的结构体类型

成功时返回目录流指针;出错时返回NULL

 

2.读取目录流中的内容:

 struct  dirent *readdir(DIR *dirp);

成功时返回目录流dirp中下一个目录项

出错或到末尾时时返回NULL

 

3.关闭一个目录文件

int closedir(DIR *dirp);

成功时返回0;出错时返回EOF

例:

    if ((dirp  = opendir(argv[1])) == NULL) {

           perror(“opendir”);  return -1;

    }

    while ((dp = readdir(dirp)) != NULL) {

        printf(“%s\n”, dp->d_name);

    }

    closedir(dirp);

 

4. 修改文件访问权限:

#include  <sys/stat.h>

 int  chmod(const char *path, mode_t mode);//chmod(“test.txt”, 0666);

 

 int  fchmod(int fd, mode_t mode);

成功时返回0;出错时返回EOF

 

5.获取文件属性:

 #include  <sys/stat.h>

 int  stat(const char *path, struct stat *buf);

 int  lstat(const char *path, struct stat *buf);

 int  fstat(int fd, struct stat *buf);

成功时返回0;出错时返回EOF

相关文章:

  • 2021-05-31
  • 2022-12-23
  • 2021-07-18
  • 2022-12-23
  • 2021-11-12
  • 2021-08-01
  • 2021-10-15
  • 2022-12-23
猜你喜欢
  • 2021-06-05
  • 2021-09-01
  • 2021-08-20
  • 2021-07-28
  • 2021-06-11
  • 2022-12-23
相关资源
相似解决方案