Dan Bradbury
Dan Bradbury

Reputation: 2116

Copying contents of a file to another using read(), write(), open()

I whipped up a quick program to simply grab the contents of a file and transpose them onto an output file. The first time I run my program I get no errors and it looks as if everything is going to work fine. However, when I check my output file there is nothing in the file. My first thought was that the permissions were not correct and writing was not allowed. When I manually created a .txt file in the directory and set the permissions and then ran the program on that it seemed to work (ubuntu is showing me the contents of the file, the copy) but I can't open the actual file. Hopefully someone with more experience than myself can help me out. Well here is my code:

int main(int argc, char* argv[]){
  char buf[128];
  int outft, inft,fileread;
  // output file opened or created
  if((outft = open(argv[1], O_CREAT | O_APPEND | O_RDWR))==-1){
    perror("open");
  }
  // lets open the input file
  inft = open(argv[2], O_RDONLY);
  if(inft >0){ // there are things to read from the input
    fileread = read(inft, buf, 160);
    printf("%s\n", buf);
    write(outft, buf, 160);
    close(inft);
  }
  close(outft);
  return 0;
}

Upvotes: 1

Views: 16276

Answers (2)

Kenster
Kenster

Reputation: 25380

Your data buffer is 128 bytes in size, but you're reading 160 bytes of data into it. This means you're writing into memory outside of the declared buffer.

I expect that the variables outft, inft, and fileread probably follow buf in memory, and are being overwritten with garbage during the read() call. The call to write() is probably failing because it's getting a garbage value for the file descriptor to write to.

To avoid the buffer overflow, sizeof is your friend:

fileread = read(inft, buf, sizeof(buf));
...
write(outft, buf, fileread);

Upvotes: 2

paulsm4
paulsm4

Reputation: 121599

Be sure to set the file permissions, too.

EXAMPLE:

if((outft = open(argv[1], O_CREAT | O_APPEND | O_RDWR, 0666))==-1){
    perror("open");
  }

Upvotes: 3

Related Questions