gpt4 book ai didi

c - 有没有办法不用打开直接从一个文件夹复制文件到另一个文件夹

转载 作者:太空宇宙 更新时间:2023-11-04 05:53:23 25 4
gpt4 key购买 nike

我知道这种复制文件的方式,我认为这是用 C 语言复制文件的标准方式。

#include <stdio.h>
#include <stdlib.h>

int main()
{
char ch, source_file[20], target_file[20];
FILE *source, *target;

printf("Enter name of file to copy\n");
gets(source_file);

source = fopen(source_file, "r");

if( source == NULL )
{
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}

printf("Enter name of target file\n");
gets(target_file);

target = fopen(target_file, "w");

if( target == NULL )
{
fclose(source);
printf("Press any key to exit...\n");
exit(EXIT_FAILURE);
}

while( ( ch = fgetc(source) ) != EOF )
fputc(ch, target);

printf("File copied successfully.\n");

fclose(source);
fclose(target);

return 0;

但这种方式打开文件并逐行复制。我要复制的文件很大而且很多。这种方式需要非常非常长的时间。有没有办法可以实现直接复制这些文件的目标。我知道终端或命令提示符与 C 语言完全不同,但是一个简单的

cp sourcefile.txt destinationfile.txt

可以做到这一点。

C 语言中是否有我可以使用的此类命令或技巧。我不能使用

system("cp sourcefile.txt destinationfile.txt");

命令,因为我正在编写一个应该在 Linux 和 Windows 中运行的健壮程序。

最佳答案

那么,您认为 cp 命令本身对复制文件有何作用?如果以读取模式打开源文件,目标文件是写入模式并通过二进制 block 复制所有内容!好的,如果您将其他选项传递给 cp,则可以涉及更多内容,但副本本身并不比这更神奇。

话虽这么说,但您所做的并非如此。您正在逐个字符地复制文件。即使标准库做了一些缓冲,您还是在可以避免的时候重复调用一个函数。并且... 永远不要使用 gets。它已被弃用多年,因为它不安全。如果用户输入太长的文件名(超过 19 个字符),就会出现缓冲区溢出。并且不要忘记测试所有 io 函数,包括输出函数。当在 USB key 等外部媒体上写入一个巨大的文件时,您可能会用完设备上的空间,而您的程序只会说它可以成功完成复制。

复制循环可能是这样的:

#define SIZE 16384
char buffer[SIZE];
int crin, crout = 0;

while ((crin = fread(buffer, 1, SIZE, source)) > 0) {
crout = fwrite(buffer, 1, crin, target);
if (crout != crin) { /* control everything could be written */
perror("Write error");
crout = -1;
break;
}
if (crin < 0) { /* test read error (removal of amovible media, ...) */
perror("Read error");
}

这里的低级优化是直接使用 posix 函数而不是标准库函数,因为一旦你在大块中使用二进制 IO,标准库的缓冲就没有优势,你只会有它的开销.

关于c - 有没有办法不用打开直接从一个文件夹复制文件到另一个文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33526489/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com