我是一个编程新手,想发一个我一直在努力解决的问题。
我需要用c语言写一个程序,使用unix系统调用来复制一个文件夹中所有相同扩展名的文件。
我试过很多程序,但似乎都不能完成这项工作。请你给我提供一个解决方案。是的,我已经没有地方可找了。
我已经试过了。
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
void usage(char *name)
{
printf("Usage: %s <source> <destination>\n", name);
}
int main(int argc, char *argv[])
{
int fd1, fd2;
int n;
char c;
/*** command line args */
if(argc!=3)
{
usage(argv[0]);
exit(1);
}
/*** open the files */
if((fd1=open(argv[1], O_RDONLY))<0)
{
printf("Error opening input file\n");
exit(2);
}
if((fd2=open(argv[2], O_WRONLY | O_CREAT | O_EXCL, S_IRWXU)) < 0)
{
printf("Error creating destination file\n");
exit(3);
}
/*** copy */
while((n = read(fd1, &c, sizeof(char))) > 0)
{
if(write(fd2, &c, n) < 0)
{
printf("Error writing to file\n");
exit(4);
}
}
if(n < 0)
{
printf("Error reading from file\n");
exit(5);
}
/*** closing the files */
close(fd1);
close(fd2);
return 0;
}
但没有成功,它返回:
"创建目标文件错误"
请帮助我
我想我找到了一个更简单的方法。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char command[50];
strcpy(command, "cp -v *.txt ~/folder/folder1");
system(command);
return 0;
}
它可以完成这个任务 你觉得这里有什么问题吗?