【问题标题】:copying content of one file to other using system calls使用系统调用将一个文件的内容复制到另一个文件
【发布时间】:2013-07-31 09:03:33
【问题描述】:

在这里,我尝试使用 open readwrite 系统调用将一个文件的内容复制到其他(unix)中,但由于某种原因,代码运行了无限时间... 我没有收到错误,所以如果你能帮助我!!

#include<unistd.h>
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
int main(int args,char *ar[])
{
char *source=ar[1];
char *dest="def.txt";
char *buf=(char *)malloc(sizeof(char)*120);
int fd1,fd2;
fd1=open(source,O_CREAT,0744);
fd2=open(dest,O_CREAT,0744);
while(read(fd1,buf,120)!=-1)
{
printf("%s",buf);
//printf("Processing\n");
write(fd2,buf,120);
}
printf("Process Done");
close(fd1);
close(fd2);
}

提前谢谢...

【问题讨论】:

    标签: c unix system-calls


    【解决方案1】:

    您的代码中有很多问题。

    • 首先也是最明显的是,您永远不会检查错误(mallocopenclose)。如果您想知道:是的,您确实需要查看close
    • 那么您的open 调用不正确,因为您没有指定文件访问模式。引用 man 2 open: The argument flags must include one of the following access modes: O_RDONLY, O_WRONLY, or O_RDWR. 你在这里调用未定义的行为。
    • 您对read 的返回值的处理也是错误的。您只检查错误,但如果没有发生错误,您的程序将无限循环。请注意,文件结尾不被视为错误。相反,read 返回读取的字节数(您不检查)。在文件结束时,返回值为 0。
    • 您的主函数没有返回值。尝试运行 gccclang-Wall -Wextra 以查看此类问题。
    • 顺便说一句,强制转换malloc 的返回值被认为是有害的。

    【讨论】:

      猜你喜欢
      • 2015-07-17
      • 1970-01-01
      • 2018-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      相关资源
      最近更新 更多