怎么用C语言复制文件或者移动文件,不要用system的命令。Linux命令cp cat都不行,我要

怎么用C语言复制文件或者移动文件,不要用system的命令。Linux命令cp cat都不行,我要C代码

要求 c:\source.txt文件必须存在,可以自己建立一个这样的文本文件,并输入一些数据,以便测试。
复制文件:源文件c:\source.txt 复制到c:\dex.txt
#include<stdio.h>
void main()
{
FILE *fp1,*fp2;
char str1;
fp2=fopen("c:\\des.txt","w");
if((fp1=fopen("C:\\source.txt","r"))==NULL)
{
printf("file cannot be opened\n");
return;
}
while((str1=fgetc(fp1))!=EOF)
fputc(str1,fp2);
fclose(fp1);
fclose(fp2);
}
希望能够帮到你。

移动文件:源文件c:\source.txt 移动到c:\dex.txt
#include<stdio.h>
void main()
{
FILE *fp1,*fp2;
char str1;
fp2=fopen("c:\\des.txt","w");
if((fp1=fopen("C:\\source.txt","r"))==NULL)
{
printf("file cannot be opened\n");
return;
}
while((str1=fgetc(fp1))!=EOF)
fputc(str1,fp2);
fclose(fp1);
fclose(fp2);
remove("c:\\source.txt");
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2015-01-26
这里有误解,c语言本身是不提供这两种文件操作函数的,要完成该功能就需要操作系统命令,或者理解底层硬件接口,自己编写驱动程序操作文件,不会有通用代码的。
第2个回答  2015-01-26
CopyFile,有这个API的
移动的话只能自己写一个算法了,将原来的数据写到目标路径中,然后把原来的数据删除
第3个回答  2015-01-26
/*
* create by bdkyr
* date 2015-1-26
*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc,char* argv[]){
int fd1,fd2;
char buffer[100];
int num;

if(argc!=3){
printf("Usage : %s source dest",argv[0]);
return 1;
}

if((fd1=open(argv[1],O_RDONLY))==-1){
perror("Cannot open the file");
return 1;
}

if((fd2=open(argv[2],O_CREAT | O_WRONLY,0777))==-1){
perror("Cannot create the destination file");
return 1;
}

while((num=read(fd1,buffer,100))>0){

if(write(fd2,buffer,num)==-1){
perror("Cannot write the file content to the file");
return 1;
}

}

close(fd1);
close(fd2);
return 0;
}
第4个回答  2015-01-26

追问

有没有具体函数api直接调用的

copy这类直接调用的函数

追答

拷贝文件是一个耗时较长并且复杂的操作,即使有些系统提供了系统lib来实现文件copy(比如windows CopyFile), 但是也没有倾向表明会有一个POSIX 系统文件copy函数。附windows CopyFile:
BOOL WINAPI CopyFile(
_In_ LPCTSTR lpExistingFileName,
_In_ LPCTSTR lpNewFileName,
_In_ BOOL bFailIfExists
);

本回答被提问者采纳
相似回答