这似乎是一个简单的问题,但我在这里没有找到任何类似的东西。
由于C中没有文件复制功能,我们必须自己实现文件复制,但是我不喜欢为这种琐碎的事情而重新发明轮子,所以我想问一下云:
此代码应该是可移植的(windows / mac / linux / bsd / qnx / younameit),稳定,经过时间测试,快速,内存高效等。欢迎进入特定系统的内部以获取更多性能(例如获取文件系统集群)大小)。
这似乎是一个琐碎的问题,但是,例如,CP命令的源代码不是10行C代码。
就实际的I / O而言,我已经以各种形式编写了一百万遍用于将数据从一个流复制到另一个流的代码。如果成功,它将返回0,如果错误,则返回-1,并设置errno(在这种情况下,可能已经复制了任意数量的字节)。
注意,对于常规文件,您可以跳过EAGAIN的内容,因为常规文件始终会阻塞I / O。但是不可避免地,如果您编写此代码,则有人会在其他类型的文件描述符上使用它,因此将其视为免费赠品。
[GNU cp
有一个特定于文件的优化,在这里我没有打扰,对于0字节的长块而不是写,只是通过寻找结尾来扩展输出文件。
void block(int fd, int event) {
pollfd topoll;
topoll.fd = fd;
topoll.events = event;
poll(&topoll, 1, -1);
// no need to check errors - if the stream is bust then the
// next read/write will tell us
}
int copy_data_buffer(int fdin, int fdout, void *buf, size_t bufsize) {
for(;;) {
void *pos;
// read data to buffer
ssize_t bytestowrite = read(fdin, buf, bufsize);
if (bytestowrite == 0) break; // end of input
if (bytestowrite == -1) {
if (errno == EINTR) continue; // signal handled
if (errno == EAGAIN) {
block(fdin, POLLIN);
continue;
}
return -1; // error
}
// write data from buffer
pos = buf;
while (bytestowrite > 0) {
ssize_t bytes_written = write(fdout, pos, bytestowrite);
if (bytes_written == -1) {
if (errno == EINTR) continue; // signal handled
if (errno == EAGAIN) {
block(fdout, POLLOUT);
continue;
}
return -1; // error
}
bytestowrite -= bytes_written;
pos += bytes_written;
}
}
return 0; // success
}
// Default value. I think it will get close to maximum speed on most
// systems, short of using mmap etc. But porters / integrators
// might want to set it smaller, if the system is very memory
// constrained and they don't want this routine to starve
// concurrent ops of memory. And they might want to set it larger
// if I'm completely wrong and larger buffers improve performance.
// It's worth trying several MB at least once, although with huge
// allocations you have to watch for the linux
// "crash on access instead of returning 0" behaviour for failed malloc.
#ifndef FILECOPY_BUFFER_SIZE
#define FILECOPY_BUFFER_SIZE (64*1024)
#endif
int copy_data(int fdin, int fdout) {
// optional exercise for reader: take the file size as a parameter,
// and don't use a buffer any bigger than that. This prevents
// memory-hogging if FILECOPY_BUFFER_SIZE is very large and the file
// is small.
for (size_t bufsize = FILECOPY_BUFFER_SIZE; bufsize >= 256; bufsize /= 2) {
void *buffer = malloc(bufsize);
if (buffer != NULL) {
int result = copy_data_buffer(fdin, fdout, buffer, bufsize);
free(buffer);
return result;
}
}
// could use a stack buffer here instead of failing, if desired.
// 128 bytes ought to fit on any stack worth having, but again
// this could be made configurable.
return -1; // errno is ENOMEM
}
打开输入文件:
int fdin = open(infile, O_RDONLY|O_BINARY, 0);
if (fdin == -1) return -1;
打开输出文件很棘手。作为基础,您需要:
int fdout = open(outfile, O_WRONLY|O_BINARY|O_CREAT|O_TRUNC, 0x1ff);
if (fdout == -1) {
close(fdin);
return -1;
}
但是有一些混杂因素:
cp -i
。显然,所有这些问题的答案都可能是“与cp
相同”。在这种情况下,原始问题的答案是“忽略我或任何其他人所说的一切,并使用cp
的来源”。
Btw,获取文件系统的群集大小几乎是无用的。经过磁盘块的大小之后,几乎总会看到速度随着缓冲区大小的增加而增加。
[这是我需要使用测试工具将一个文件复制到另一个文件时使用的功能:
/*
@(#)File: $RCSfile: fcopy.c,v $
@(#)Version: $Revision: 1.11 $
@(#)Last changed: $Date: 2008/02/11 07:28:06 $
@(#)Purpose: Copy the rest of file1 to file2
@(#)Author: J Leffler
@(#)Modified: 1991,1997,2000,2003,2005,2008
*/
/*TABSTOP=4*/
#include "jlss.h"
#include "stderr.h"
#ifndef lint
/* Prevent over-aggressive optimizers from eliminating ID string */
const char jlss_id_fcopy_c[] = "@(#)$Id: fcopy.c,v 1.11 2008/02/11 07:28:06 jleffler Exp $";
#endif /* lint */
void fcopy(FILE *f1, FILE *f2)
{
char buffer[BUFSIZ];
size_t n;
while ((n = fread(buffer, sizeof(char), sizeof(buffer), f1)) > 0)
{
if (fwrite(buffer, sizeof(char), n, f2) != n)
err_syserr("write failed\n");
}
}
#ifdef TEST
int main(int argc, char **argv)
{
FILE *fp1;
FILE *fp2;
err_setarg0(argv[0]);
if (argc != 3)
err_usage("from to");
if ((fp1 = fopen(argv[1], "rb")) == 0)
err_syserr("cannot open file %s for reading\n", argv[1]);
if ((fp2 = fopen(argv[2], "wb")) == 0)
err_syserr("cannot open file %s for writing\n", argv[2]);
fcopy(fp1, fp2);
return(0);
}
#endif /* TEST */
显然,此版本使用来自标准I / O的文件指针,而不使用文件描述符,但是它相当有效,并且具有尽可能的可移植性。
好吧,除了误差函数-这对我来说是特有的。只要您能够正确处理错误,就可以了。 "jlss.h"
标头声明为fcopy()
; "stderr.h"
标头在许多其他类似的错误报告功能中声明了err_syserr()
。下面是该函数的一个简单版本-真正的函数会添加程序名称并执行其他操作。
#include "stderr.h"
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
void err_syserr(const char *fmt, ...)
{
int errnum = errno;
va_list args;
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
if (errnum != 0)
fprintf(stderr, "(%d: %s)\n", errnum, strerror(errnum));
exit(1);
}
上面的代码可能会被视为具有您选择的现代BSD许可证或GPL v3。
每次读取的大小需要为512的倍数(扇区大小),4096为佳]
这里是一个非常简单明了的例子:Copy a file。由于它是用ANSI-C编写的,没有任何特定的函数调用,所以我认为这将是可移植的。
取决于您复制文件的意思,当然这并非易事。如果您只打算复制内容,那么几乎没有任何事可做。但是通常,您需要复制文件的元数据,并且这肯定与平台有关。我不知道有任何C库以可移植的方式完成您想要的工作。如果您关心可移植性,那么仅处理文件名本身并不是一件容易的事。
在C ++中,boost中有文件库>
我在实现自己的文件副本时发现的一件事,似乎很明显,但事实并非如此:I / O是slow
[史蒂夫·杰索普(Steve Jessop)接受的答案没有回答问题的第一部分,乔纳森·莱弗勒(Jonathan Leffler)做到了,但是做错了:代码应该写成]]
while ((n = fread (buffer, 1, sizeof(buffer), f1)) > 0)
if (fwrite(buffer, n, 1, f2) != 1)
/* we got write error here */
/* test ferror(f1) to a read errors */