Unix Programming :文件IO

时间:2023-03-08 19:14:55

文件描述符常量(unistd.h):

  • STDIN_FILENO
  • STDOUT_FILENO
  • STDERR_FILENO

通常这些常量分别对应于数字0,1,2

文件操作需要头文件 fcntl.h ,一些常量需要头文件unistd.h

  • open int open(const char *pathname, int oflag, ... )
    • 其中oflag可以是以下值的集合

      • O_RDONLY、O_WRONLY、O_RDWR 读写属性
      • O_APPEND、O_CREAT、O_EXCL、O_TRUNC、O_NOCTTY、O_NONBLOCK
  • creat 等效于 open (pathname, O_WRONLY | O_CREAT | O_TRUNC, mode);
  • closeint close(int filedes);
  • lseek off_t lseek(int filedes, off_t offset, int whence); 
    • 与偏移 offset 相对的位置whence:

      • SEEK_SET 文件起始
      • SEEK_CUR 当前位置
      • SEEK_END 文件末尾
  • write ssize_t write(int filedes, const void *buf, size_t nbytes);

生成有洞的文件

使用lseek跳到文件原大小之外的范围然后写入数据,那么中间的部分数据不会被真正存储,不过读取是都当做0看待,但ls看到的文件大小还是将中间这些算进去的,这样可以非常快速的生成较大的空白文件。

 #include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <limits.h>
#include <string.h> char file_header[] = "this is the file header msg.";
char file_end[] = "now we reach the file end."; int main() {
printf("size of off_t: %ld\n", sizeof(off_t));
printf("max file open number: %ld\n", sysconf(_SC_OPEN_MAX));
printf("max name length: %d\n", _POSIX_NAME_MAX);
printf("max path length: %d\n", _POSIX_PATH_MAX); int fd = open("tmpfile", O_RDWR | O_CREAT | O_TRUNC); if (fd < ) {
perror("file operation open");
return ;
} int head_len = strlen(file_header);
int end_len = strlen(file_end); if (write(fd, file_header, head_len) != head_len) {
perror("write file header msg failed.");
} if (lseek(fd, , SEEK_SET) == -) {
perror("lseek failed.");
} if (write(fd, file_end, end_len) != end_len) {
perror("write file end msg failed.");
} if (close(fd) < ) {
perror("file operation close");
}
return ;
}

Unix Programming :文件IO

缓存影响I/O效率

由于有预读取的过程存在使用缓存可以提高复制速度,但是当缓存超过其预读取大小时缓存作用就降低了

 #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h> char buffer[ * ]; int main(int argc, char* argv[]) {
if (argc < ) {
fprintf(stderr, "usage:\n\t%s <buffer_size>\n", argv[]);
return ;
} int buffer_size = ;
sscanf(argv[], "%d", &buffer_size); if (buffer_size > sizeof(buffer)) {
fprintf(stderr, "buffer size too big. max: %ld\n", sizeof(buffer));
return ;
} int bytes_read = ; while ((bytes_read = read(STDIN_FILENO, buffer, buffer_size)) > ) {
if (write(STDOUT_FILENO, buffer, bytes_read) != bytes_read) {
fprintf(stderr, "write error.\n");
}
} if (bytes_read < ) {
fprintf(stderr, "read error.\n");
} return ;
}

测试了使用不同缓存的情况下IO效率(比较随意):

Unix Programming :文件IO

Linux中的fd设备

Unix Programming :文件IO