简体   繁体   中英

How to write to a file using read system call ? and how to decide the buffer size?

i am writing a code that reads from a file and write to the other file, i am having a problem deciding what to put the buffer size, because i don't know, it could be any file, also how to read from a file using while loop? :

here i opened the first file:

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

and here i opened the seconed file:

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;
            }
          }

and here is how i am trying to read:

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 ;

You should read up on pointers. The read function wants a pointer to use. A traditional solution looks like

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

That is because the name of an array is a pointer to the first element in the array.

If you only want to read one byte at a time, I suggesting doing what I did below, and changing buff to a char (not a ptr to char), and simply passing the address of buff with the &

 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 ;

Let me know if that does not work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM