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

坚强是说给别人听的谎言 提交于 2019-12-08 04:13:56

问题


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;
}

回答1:


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);



回答2:


Be sure to set the file permissions, too.

EXAMPLE:

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


来源:https://stackoverflow.com/questions/9219079/copying-contents-of-a-file-to-another-using-read-write-open

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!