使用read(),write(),open()将文件内容复制到另一个文件

时间:2012-02-09 21:28:10

标签: c file-io copy

我掀起了一个快速程序来简单地抓取文件的内容并将它们转置到输出文件中。我第一次运行程序时没有出现任何错误,看起来好像一切正​​常。但是,当我检查输出文件时,文件中没有任何内容。我的第一个想法是权限不正确,不允许写入。当我在目录中手动创建.txt文件并设置权限然后运行该程序时它似乎工作(ubuntu向我显示文件的内容,副本)但我无法打开实际文件。 希望有比我更多经验的人可以帮助我。 那么这是我的代码:

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

2 个答案:

答案 0 :(得分:3)

请务必同时设置文件权限。

实施例

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

答案 1 :(得分:2)

您的数据缓冲区大小为128字节,但您正在读取160字节的数据。这意味着你要在声明的缓冲区之外写入内存。

我希望变量outft, inft, and fileread可能跟在内存中的buf,并且在read()调用期间被垃圾覆盖。对write()的调用可能失败了,因为它正在为要写入的文件描述符获取垃圾值。

为避免缓冲区溢出,sizeof是您的朋友:

fileread = read(inft, buf, sizeof(buf));
...
write(outft, buf, fileread);
相关问题