gpt4 book ai didi

delphi - 如何告诉 CreateFile 我想要附加到现有文件?

转载 作者:行者123 更新时间:2023-12-03 15:52:16 30 4
gpt4 key购买 nike

我正在使用 Delphi 2010,并正在寻找一种使用 CreateFile Windows API 函数追加数据而不是在指定文件中覆盖数据的方法?

我并不是在寻找一种可选的方法来做到这一点,例如 Append() 或 Rewrite() 或类似的方法。我正在专门寻找通过使用 CreateFile Windows API 函数来执行此操作。

我尝试使用:

// this will open existing file but will **overwrite** data in the file.
fHandle:= CreateFile(PChar(FName), GENERIC_READ or GENERIC_WRITE, 0,
nil, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);

// this will recreate file each time therefore deleting its original content
fHandle:= CreateFile(PChar(FName), GENERIC_READ or GENERIC_WRITE, 0,
nil, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

非常感谢,

最佳答案

我怀疑OPEN_ALWAYS实际上就是你在这里所需要的。

Opens a file, always. If the specified file exists, the function succeeds and the last-error code is set to ERROR_ALREADY_EXISTS (183).

If the specified file does not exist and is a valid path to a writable location, the function creates a file and the last-error code is set to zero.

如果您正在写作,则可以删除 GENERIC_READ

我预计的另一个问题是,当打开文件时,文件位置被设置为文件的开头。寻求最终解决这个问题。

Win32Check(SetFilePointerEx(fHandle, 0, nil, FILE_END));

或者您可以使用 FILE_APPEND_DATA而不是GENERIC_WRITE

Handle:= CreateFile(PChar(Name), FILE_APPEND_DATA, 0, 
nil, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);

当您使用FILE_APPEND_DATA时,如果您没有同时使用FILE_WRITE_DATA,则所有写入都会写入文件末尾,无论文件的当前值如何指针。

documentation是这样说的:

For a file object, the right to append data to the file. (For local files, write operations will not overwrite existing data if this flag is specified without FILE_WRITE_DATA.)

请注意,旧版本的 Delphi 没有定义 FILE_APPEND_DATA,因此您需要:

const
FILE_APPEND_DATA = $0004;
<小时/>

综上所述,我怀疑流或编写器类在这里是更好的选择。您确定要深入了解 Win32 API 吗?

关于delphi - 如何告诉 CreateFile 我想要附加到现有文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23094225/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com