在 C++ 中复制部分文件
我目前正忙于一个项目,在该项目中我必须将一个文件的一部分复制到另一个文件,因此我使用 fread 和 fwrite 编写了一个代码。但我遇到了一个问题:出于测试目的,我编写了一个应该复制整个文件的代码,但不知何故该代码创建了比原始文件更大的副本。请参阅下面我编写的代码
FILE *base_file;
FILE *new_file;
fpos_t curpos;
int tmp;
// Open the base file
fopen_s(&base_file, "C:/base.dat", "rb");
// Open the file which should contain the copy
fopen_s(&new_file, "C:/new.dat", "w");
// Get the filesize
fseek(base_file, 0, SEEK_END);
fgetpos(base_file, &curpos);
fseek(base_file, 0, SEEK_SET);
//Read and copy (it seems to go wrong here)
for(int i = 0; i < curpos; i++){
fread (&tmp, 1, 1, base_file);
fwrite(&tmp, 1, 1, new_file);
}
fclose(base_file);
fclose(new_file);
基本文件为 525 kb,新文件为 527kb。据我所知,发生此问题的部分是在有 7 个空字节的部分之后,并且副本以某种方式在这些部分之后添加了“0D”(十六进制)。在 ascii 中,“0D”字符是“回车符”。我想知道我的复制代码在文件中添加回车符的原因是什么?据我所知,这个脚本应该像我刚刚读取基本文件一样工作,并将其直接复制到新文件,并且基本文件不包含这些回车符。
I'm currently busy with a project in which I have to copy a part from a file to another file, so I made a code for that using fread and fwrite. But I came across a problem: for testing purposes I made a code which should copy a whole file, but somehow the code creates copies that are larger than the original file. See the code I made below
FILE *base_file;
FILE *new_file;
fpos_t curpos;
int tmp;
// Open the base file
fopen_s(&base_file, "C:/base.dat", "rb");
// Open the file which should contain the copy
fopen_s(&new_file, "C:/new.dat", "w");
// Get the filesize
fseek(base_file, 0, SEEK_END);
fgetpos(base_file, &curpos);
fseek(base_file, 0, SEEK_SET);
//Read and copy (it seems to go wrong here)
for(int i = 0; i < curpos; i++){
fread (&tmp, 1, 1, base_file);
fwrite(&tmp, 1, 1, new_file);
}
fclose(base_file);
fclose(new_file);
The base file is 525 kb, and the newfile is 527kb. As far as I could see the parts where this problem occurs is after parts where there are 7 nullbytes, and the copy somehow has added a '0D'(in Hex) after these parts. In ascii the '0D' character is a 'carriage return'. I was wondering what could be the reason that my copy code adds carriage returns into the file? As far as I know this script should just work as I just read the basefile, and directly copy it to the newfile, and the basefile doesn't contain these carriage returns.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在以文本模式而不是二进制模式打开目标文件,因此换行符翻译会在您背后进行。将模式更改为
“wb”
。其他注意事项:
You're opening the destination file in text mode, instead of binary mode, so the newline translation happens behind your back. Change the mode to
"wb"
.Other notes:
用“wb”代替“w”可以解决这个问题吗?
Will "wb" instead of "w" fix it?