如何在 C 语言中复制文件而不依赖于平台?
看起来这个问题非常简单,但我找不到在不依赖平台的情况下在 C 中复制文件的明确解决方案。
我在开源项目中使用了 system() 调用来创建目录、复制文件和运行外部程序。它在 Mac OS X 和其他 Unix 系统上运行得很好,但在 Windows 上却失败了。问题是:
system( "cp a.txt destination/b.txt" );
- Windows 使用反斜杠作为路径分隔符。 (与 Unix-ish 中的斜杠相比)
- Windows 使用“copy”作为内部复制命令。 (与 Unix-ish 中的 cp 相比)
如何编写没有依赖性的复制代码?
(实际上,我编写了宏来解决这个问题,但这并不酷。 http://code.google.com/p/npk/source/browse/trunk/npk/cli/tests/testutil.h,L22-56)
It looks like this question is pretty simple but I can't find the clear solution for copying files in C without platform dependency.
I used a system() call in my open source project for creating a directory, copying files and run external programs. It works very well in Mac OS X and other Unix-ish systems, but it fails on Windows. The problem was:
system( "cp a.txt destination/b.txt" );
- Windows uses backslashes for path separator. (vs slashes in Unix-ish)
- Windows uses 'copy' for the internal copy command. (vs cp in Unix-ish)
How can I write a copying code without dependency?
( Actually, I wrote macros to solve this problems, but it's not cool. http://code.google.com/p/npk/source/browse/trunk/npk/cli/tests/testutil.h, L22-56 )
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
system()
函数带来的麻烦远大于它的价值;它在单独的进程中调用 shell,通常应该避免。而是使用
fopen()
a.txt
和dest/b.text
,并使用getc()
/putc()
进行复制(因为标准库比你更有可能进行页面对齐缓冲)The
system()
function is a lot more trouble than it's worth; it invokes the shell in a seperate proccess, and should usually be avoided.Instead
fopen()
a.txt
anddest/b.text
, and usegetc()
/putc()
to do the copying (because the standard library is more likely to do page-aligned buffering than you)您需要使用stdio.h中的C标准库函数。
特别是,
fopen
、fread
、fwrite
和fclose
就足够了。请务必在
fopen
的标志中包含b
(“二进制”)选项。[编辑]
不幸的是,文件名本身(正斜杠与反斜杠)仍然依赖于平台。所以你需要某种
#ifdef
或类似的东西来处理这个问题。或者您可以使用跨平台工具包。
You need to use the C standard library functions in stdio.h.
In particular,
fopen
,fread
,fwrite
, andfclose
will be sufficient.Be sure to include the
b
("binary") option in the flags tofopen
.[edit]
Unfortunately, the file names themselves (forward-slashes vs. back-slashes) are still platform dependent. So you will need some sort of
#ifdef
or similar to deal with that.Or you can use a cross-platform toolkit.
使用标准 C 库
stdio.h
。首先使用fopen(inputFilename, "rb")
打开输入文件进行读取,使用fopen(outputFilename, "wb")
打开输出文件进行写入,使用复制内容代码>fread
和fwrire
。然后使用fclose
关闭这两个文件。Use the standard C library
stdio.h
. First open input file for reading usingfopen(inputFilename, "rb")
and open output file for writing usingfopen(outputFilename, "wb")
, copy the content usingfread
andfwrire
. Then close both files usingfclose
.