如何使用读取系统调用写入文件?以及如何确定缓冲区大小?

时间:2020-05-05 16:15:58

标签: c++ linux size system-calls

我正在编写一个从文件读取并写入另一个文件的代码,我在决定放入缓冲区大小时遇到​​了问题,因为我不知道它可以是任何文件,以及如何读取从文件使用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 ;

1 个答案:

答案 0 :(得分:0)

您应该阅读指针。读取功能需要使用指针。 传统解决方案看起来像

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

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

如果您一次只想读取一个字节,我建议您执行下面的操作,并将buff更改为char(而不是ptr更改为char),并只需将&#p的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 ;

让我知道这是否无效