复制文件的内容到另一个使用的read(),写(),开() [英] Copying contents of a file to another using read(), write(), open()

查看:192
本文介绍了复制文件的内容到另一个使用的read(),写(),开()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刮起了快速程序来简单地抓取文件的内容,并转它们放到一个输出文件。我第一次运行我的程序我没有得到任何错误,它看起来好像一切都将正常工作。然而,当我检查我的输出文件没有什么在文件中。我首先想到的是,权限是不正确的,并不允许写。当我手动创建目录中的.txt文件,并设置权限,然后运行该程序上它似乎工作(Ubuntu是显示我的文件,复制的内容),但我无法打开实际的文件。
希望有人有更多的经验比我能帮助我。
那么这里是我的code:

  INT主(INT ARGC,CHAR *的argv []){
  CHAR BUF [128];
  诠释outft,inft,FILEREAD;
  //输出文件的打开或创建
  如果((outft =打开(的argv [1],O_CREAT | O_APPEND | O_RDWR))== - 1){
    PERROR(开放);
  }
  //允许打开输入文件
  inft =打开(的argv [2],O_RDONLY);
  如果(inft大于0){//有东西从输入到读
    FILEREAD =读(inft,BUF,160);
    的printf(%S \\ n,BUF);
    写(outft,BUF,160);
    关闭(inft);
  }
  关闭(outft);
  返回0;
}


解决方案

您的数据缓冲区的大小为128字节,但你读160个字节的数据进去。这意味着你写到内存缓冲区声明之外。

我期望变量 outft,inft和FILEREAD 可能遵循 BUF 在内存中,并正在改写与阅读()通话过程中的垃圾。到通话写()很可能失败,因为它得到一个垃圾值文件描述符写入。

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

  FILEREAD =读(inft,BUF,sizeof的(BUF));
...
写(outft,BUF,FILEREAD);

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

解决方案

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

这篇关于复制文件的内容到另一个使用的read(),写(),开()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆