-4

i am trying to copy to a file the contents of two input files in c with the help of read, write and open. At first i tried to simply copy the contents of only one file that contains the 'hello' world, but this is what gets written: "hello h«Ú^?^@^@^A^@^@^@^@^@^@^@m G«Ú^?^@^@^@^@^@^@^@^@^@^@^Pjh«Ú^?^@^@^A^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^A^@^@^@þ^?^@^@°<91>h«Ú^?^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^H<95>h«Ú^?^@^@P)»Ó " my code is:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc , char *argv[]){
int fd1,fd2,fdout;
int fread1, fread2;
char buff[128];
int fconf(int f1, int f3){
fd1 = open(argv[1],O_RDONLY);

fdout = open(argv[2],O_RDONLY | O_CREAT | O_APPEND | O_RDWR);
fread1 = read(fd1,buff,sizeof(buff));    
write(fdout,buff,sizeof(buff));
 close(fd1);    
 close(fdout);
 return 0;
 }
}

I have no idea why this happens.

Theo Stef
  • 11
  • 5
  • You’re passing `sizeof buff` as the number of bytes you want written with `write`. That’s always going to be 128. `read` returns the actual number of bytes read. Also, it’s a really good idea to check for errors, and you can find out how to do that in the respective functions’ documentation. – Ry- Oct 22 '17 at 14:49
  • 'fread1 = read(fd1,buff,sizeof(buff));'.. then you ignore the value of 'fread1':( – Martin James Oct 22 '17 at 14:50
  • man read: 'On success, the number of bytes read is returned' – Martin James Oct 22 '17 at 14:50
  • Why are you passing both `O_RDONLY` and `O_RDWR` to the second `open`? – aschepler Oct 22 '17 at 14:51

1 Answers1

0

Probably your input file contains less than 128 bytes. But you always attempt to write all 128 bytes from your buffer to your output file. Bytes after what was read are uninitialized garbage.

Use the return value of read to know how many bytes you actually got.

aschepler
  • 70,891
  • 9
  • 107
  • 161