文件追写:文件 ""E:\one.txt.log"" 写到""E:\two.txt.log""

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

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

	// Open the existing file.
	hFile = CreateFile(TEXT("E:\\one.txt.log"), // open One.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 One.txt.");
		return 0;
	}

	// Open the existing file, or if the file does not exist,
	// create a new file.
	hAppend = CreateFile(TEXT("E:\\two.txt.log"), // open Two.txt
						GENERIC_WRITE,            // 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 Two.txt.");
		return 0;
	}
	// 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 finished.
	do
	{
		if (ReadFile(hFile, buff, sizeof(buff), &dwBytesRead, NULL))
		{
			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);
		}
	} while (dwBytesRead == sizeof(buff));
	// Close both files.
	CloseHandle(hFile);
	CloseHandle(hAppend);
	return 1;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值