首页 > 解决方案 > 如何使用读取系统调用写入文件?以及如何确定缓冲区大小?

问题描述

我正在编写一个从文件读取并写入另一个文件的代码,我在决定放置缓冲区大小时遇到​​问题,因为我不知道,它可能是任何文件,以及如何从文件中读取使用while循环?:

在这里我打开了第一个文件:

  int fd1 = open(args[1], O_RDONLY);
  if(fd1 == -1){
        perror("error");
        return;
  }

在这里我打开了第二个文件:

int fd2 = open(args[2], O_WRONLY|O_TRUNC);
          if (fd2 == -1) {                // if we couldn't open the file then create a new one (not sure if we supposed to this ?)
            fd2 = open(args[2], O_WRONLY|O_CREAT, 0666);
            if (fd2 == -1) {
                perror("error");
                return;
            }
          }

这就是我试图阅读的方式:

char* buff;
 int count = read(fd1, buff, 1);  /// read from the file fd1 into fd2
              while (count != -1) {
                  if (!count) {
                      break;
                  }
                  if (write(fd2, buff, 1) == -1) {
                      perror("smash error: write failed");
                      return;
                  }
                  read_res = read(fd1, buff, 1);
                  if (read_res == -1) {
                      perror("smash error: read failed");
                      return;
                  }
              }
              cout <<"file1 was coppiesd to file 2" << endl ;

标签: c++linuxsizesystem-calls

解决方案


你应该阅读指针。读取函数需要一个要使用的指针。传统的解决方案看起来像

#SIZE 255
char buff[SIZE]
int count = read(fd1, buff, SIZE)
//add logic to deal reading less then SIZE

这是因为数组的名称是指向数组中第一个元素的指针。

如果您只想一次读取一个字节,我建议按照我在下面所做的操作,将 buff 更改为 char(而不是 ptr 到 char),并简单地将 buff 的地址与 & 一起传递

 char buff;
 int count = read(fd1, &buff, 1);  /// priming read
              while (count != -1) {
                  if (!count) {
                      break;
                  }
                  if (write(fd2, &buff, 1) == -1) {
                      perror("smash error: write failed");
                      return;
                  }
                  read_res = read(fd1, &buff, 1);
                  if (read_res == -1) {
                      perror("smash error: read failed");
                      return;
                  }
              }
              cout <<"file1 was coppiesd to file 2" << endl ;

让我知道这是否不起作用


推荐阅读