C++ – Finding and replacing string tokens in a file in C++ using win32 API

c++stringwinapi

I'm trying to find a way to replace all instances of a string token in a file with another string.

How can I do this in C++ with the win32 API?

In other languages this is an easy thing to do, but in C++ I am just lost.

EDIT: For some context, this is for a WiX custom action. So portability is not a main priority, just the most simplest solution.

Best Solution

If the file fits in memory – it's simpler. Call OpenFile() to open file, GetFileSize() to determine file size, allocate enough memory, call ReadFile() to read file, then CloseFile. Do replacement in memory (use strstr() or similar function), then again OpenFile(), WriteFile(), CloseFile().

If the file is large - create a temporary file and read the source file in chunks and write filtered text to the temporary file, then call DeleteFile() to delete the original file and MoveFile() to move the filtered file.