-6

I created this program that should copy a file, just as the cp command does in UNIX, except my code copies without arguments. I've went over my program multiple times, and cannot figure out the problem. It compiles without error, and runs without error, but the output file does not have any text in it after I run the program.

user2917900
  • 29
  • 1
  • 1
  • 7
  • I changed the while loop to be: while(infile != -1). I changed the if() statements for read and write to be if(rr == 0){ exit(0);} – user2917900 Oct 14 '14 at 15:19
  • `while (infile != -1)` will loop forever. When you iterate over the file data you need to test the return valued from read(), not from open(). – Jens Oct 14 '14 at 15:23

1 Answers1

4

The open() system call returns a file descriptor, which may not be 1, so your termination condition,

 while(infile==1){

is compeletely bogus. You should test if the read() call read any input (the return value is the number of bytes read, which is zero when it hit end-of-file.) Please read the read man page... pun intended :-)

What's more, if (rr = 1) is an assignment which is always true. You should use == for comparisons.

Oh, and exit(-1)/return(-1) is just wrong (a return value at least under Unix is from 0 to 127). Programs indicate failure by returning 1 or EXIT_FAILURE from <stdlib.h>.

Jens
  • 69,818
  • 15
  • 125
  • 179
  • Thank you for such a brief response. I will show edits above, it seems to be working now! – user2917900 Oct 14 '14 at 15:17
  • Aside from the syntax error, the whole idea of claiming that reading 1 byte from a file indicates a fatal error is completely wrong. 1-byte files can exist, but your program won't be able to handle them. – nobody Oct 14 '14 at 16:19