Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 使用系统调用将一个文件的内容复制到其他文件_C_Unix_System Calls - Fatal编程技术网

C 使用系统调用将一个文件的内容复制到其他文件

C 使用系统调用将一个文件的内容复制到其他文件,c,unix,system-calls,C,Unix,System Calls,在这里,我试图使用打开读取和写入系统调用将一个文件的内容复制到另一个(unix)文件中,但由于某些原因,代码运行时间不长。。。 我没有得到错误,所以如果你能帮助我 #include<unistd.h> #include<stdio.h> #include<sys/types.h> #include<fcntl.h> #include<stdlib.h> #include<string.h> int main(int args

在这里,我试图使用
打开
读取
写入
系统调用将一个文件的内容复制到另一个(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);
}
#包括
#包括
#包括
#包括
#包括
#包括
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=开放(源代码,O_CREAT,0744);
fd2=打开(目的地,O_CREAT,0744);
while(读(fd1,buf,120)!=-1)
{
printf(“%s”,buf);
//printf(“处理”);
写入(fd2,buf,120);
}
printf(“过程完成”);
关闭(fd1);
关闭(fd2);
}

Thanx提前…

您的代码中有很多问题

  • 首先也是最明显的一点是,您从不检查错误(
    malloc
    open
    close
    )。如果您想知道:是的,您确实需要检查
    关闭
  • 然后,您的
    open
    调用不正确,因为您没有指定文件访问模式。引用
    man 2 open
    参数标志必须包括以下访问模式之一:O_RDONLY、O_WRONLY或O_RDWR。
    您在这里调用的是未定义的行为
  • 另外,您对
    read
    返回值的处理是错误的。您只检查错误,但如果没有错误发生,您的程序将无限期地循环。请注意,文件结尾不被视为错误。相反,
    read
    返回读取的字节数(您不检查)。文件结束时,返回值为0
  • 主函数不返回值。尝试使用
    -Wall-Wextra
    运行
    gcc
    clang
    ,查看类似问题
  • 顺便说一句,铸造
    malloc
    的返回值被认为是有害的