Copying Files using System Calls

0

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

After some research I did get 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 there were 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:

'

    
asked by anonymous 25.10.2018 / 19:29

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 the precedence of operators: the way it is, it's as if it's written

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

The correct way 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 make the 128-byte block copy, 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. It could be for example the editor "gvim".

    
25.10.2018 / 19:49