青春时代是一个短暂的美梦,当你醒来时,它早已消失得无影无踪了。
 
夜月琉璃Lv46   
window平台上copy /b 两个文件 本质上是如何实现的?     

原文转载自:https://www.zhihu.com/question/27971703   作者:pezy
根据 Appending Binary Files Using the COPY Command 可粗略的认为,就是以二进制的方式合并两个文件到一个新文件中。

举例说明:

echo Hello > 1.txt
echo World > 2.txt
copy /b 1.txt+2.txt 3.txt

那么此刻 3.txt 中应该是

Hello
World


如果仅仅实现上述例子中的基本功能,使用几个系统的 API 就可以搞定。代码如下:

#include <windows.h>
#include <stdio.h>

void main()
{
	HANDLE hFile;
	HANDLE hAppend;
	DWORD  dwBytesRead, dwBytesWritten, dwPos;
	BYTE   buff[4096];

	// Copy the existing file.

	BOOL bCopy = CopyFile(TEXT("1.txt"), TEXT("3.txt"), TRUE);
	if (!bCopy)
	{
		printf("Could not copy 1.txt to 3.txt.");
		return;
	}

	// Open the existing file.

	hFile = CreateFile(TEXT("2.txt"), // open 2.txt
		GENERIC_READ,             // open for reading
		0,                        // do not share
		NULL,                     // no security
		OPEN_EXISTING,            // existing file only
		FILE_ATTRIBUTE_NORMAL,    // normal file
		NULL);                    // no attr. template

	if (hFile == INVALID_HANDLE_VALUE)
	{
		printf("Could not open 2.txt.");
		return;
	}

	// Open the existing file, or if the file does not exist,
	// create a new file.

	hAppend = CreateFile(TEXT("3.txt"), // open 3.txt
		FILE_APPEND_DATA,         // open for writing
		FILE_SHARE_READ,          // allow multiple readers
		NULL,                     // no security
		OPEN_ALWAYS,              // open or create
		FILE_ATTRIBUTE_NORMAL,    // normal file
		NULL);                    // no attr. template

	if (hAppend == INVALID_HANDLE_VALUE)
	{
		printf("Could not open 3.txt.");
		return;
	}

	// Append the first file to the end of the second file.
	// Lock the second file to prevent another process from
	// accessing it while writing to it. Unlock the
	// file when writing is complete.

	while (ReadFile(hFile, buff, sizeof(buff), &dwBytesRead, NULL)
		&& dwBytesRead > 0)
	{
		dwPos = SetFilePointer(hAppend, 0, NULL, FILE_END);
		LockFile(hAppend, dwPos, 0, dwBytesRead, 0);
		WriteFile(hAppend, buff, dwBytesRead, &dwBytesWritten, NULL);
		UnlockFile(hAppend, dwPos, 0, dwBytesRead, 0);
	}

	// Close both files.

	CloseHandle(hFile);
	CloseHandle(hAppend);
}


将代码中的 1.txt, 2.txt, 3.txt 改为任何别的文件,是一样的。如题主补充的要求,做如下替换即可:

1.txt -> a.jpg
2.txt -> b.txt
3.txt -> c.txt (文本),c.jpg(更改后缀,成为图片)

诸如 jpg 之类的格式,依然是二进制文件,经过渲染,表现为图片而已。
 5  已被阅读了5582次  楼主 2017-08-23 14:08:22
回复列表

回复:window平台上copy /b 两个文件 本质上是如何实现的?

桂公网安备 45010302000666号 桂ICP备14001770-3号
感谢景安网络提供数据空间
本站CDN由七牛云提供支持
网站已接入ipv6
免责声明: 本网不承担任何由内容提供商提供的信息所引起的争议和法律责任。
如果某些内容侵犯了您的权益,请通过右侧按钮与我们联系
Your IP: 18.189.145.20 , 2024-04-20 02:11:53 , Processed in 0.14391 second(s).
Powered by HadSky 8.3.7
知道创宇云安全