Copying Files using System Calls

Asked

Viewed 41 times

0

I’m having trouble using write(), read(), close(), open() functions to copy a text file to a new file (previously created).

After some research I obtained the following code:

#include <fcntl.h>
int main(int argc, char * argv[])
{
    char ch;
  // FILE *source, *dest;
int n, iDest, iSource;

if(argc!=3){
    exit(1);
}
   iSource = open(argv[1], O_RDONLY);

   if (iSource == -1)
   {
      exit(1);
   }

   iDest = open(argv[2], O_WRONLY);

   if (iDest == -1)
   {
      close(iSource);
      exit(1);
   }
    while (n = read(iSource, &ch, 1) > 0){
  write(iDest, &ch, 128);
}

close(iSource);
    close(iDest);

   return 0;
}

Initially I had 2 errors saying that O_RDONLY and O_WONLY were not declared. After a search I decided to use "#include fcntl. h" but I still have problems. This time what happens when I open the destination file is as follows:

inserir a descrição da imagem aqui `

1 answer

1


This is wrong:

while (n = read(iSource, &ch, 1) > 0)
{
  write(iDest, &ch, 128);
}

you are reading 1 byte and writing 128.

UPDATE:
the above code is also wrong because of operator precedence: the way it is, it is as if it were written

while (n = (read(iSource, &ch, 1) > 0))
{
  write(iDest, &ch, 128);
}

the correct is to force the execution order explicitly with the parentheses:

while ((n = read(iSource, &ch, 1)) > 0)
{
  write(iDest, &ch, 128);
}

Assuming you want to copy in 128 byte blocks, you need to make the following changes:

...
char ch[128];
...
...
...
while ((n = read(iSource, ch, 128)) > 0)
{
  write(iDest, ch, n);
}

As for the message "the Document was not UTF-8 Valid", use an editor that accepts any content, not just files with UTF-8 content. Could be for example the editor "gvim".

  • Thank you very much! But yes my problem was in reading bytes. I just wanted to read one at a time and while copying an old code I forgot to change.

  • Could you mark the answer as please accept ? is the symbol on the left, right there under the fledgling down

Browser other questions tagged

You are not signed in. Login or sign up in order to post.