I had the same situation as yours, where a log file is continuously written by some app and I have to clear the content without closing the app. Fortunately I have only 1 file and I can open it in Notepad++, press Ctrl+A then press Delete. In case there are multiple files just use the following PowerShell script
Get-ChildItem -Recurse log*.txt | ForEach-Object {
$fs = [IO.FileStream]::new($_.FullName, `
[IO.FileMode]::Truncate, [IO.FileAccess]::Write, [IO.FileShare]::Write)
$fs.Close()
}
(Alternatively call $fs.SetLength(0) to truncate the file if [IO.FileMode] is not Truncate)
This works because the log file was opened in FILE_SHARE_WRITE mode, contrary to many people's beliefs that you can't delete or edit a file in Windows while it's opened. Subsequent opens must also be in shared mode. That's why > or >> in cmd or PowerShell doesn't work, because they open the file normally. Here's a very simple C++ to demonstrate how to create a file in shared mode
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <fileapi.h>
#include <cstdlib>
#include <ctime>
#include <cstdio>
int main() {
srand(unsigned(time(nullptr)));
const wchar_t* fileName = LR"(D:\logs\log1.txt)";
// Create file with shared read/write permission
HANDLE h = CreateFile(fileName,
GENERIC_WRITE, // open for writing
FILE_SHARE_READ | FILE_SHARE_WRITE, // share for reading/writing
NULL, // default security
CREATE_NEW,
FILE_ATTRIBUTE_NORMAL, // normal file
NULL); // no attr. template
if (h) {
for (int i = 0; i < 100; i++) {
DWORD n;
char str[64];
int l = sprintf_s(str, sizeof str, "%d: %d\n", i, rand());
WriteFile(h, str, l, &n, NULL); FlushFileBuffers(h);
Sleep(3000);
}
CloseHandle(h);
}
}
It creates log1.txt and writes to it periodically. I also have the below PowerShell script to create another shared log file
$fs = [IO.FileStream]::new('D:\logs\log2.txt', `
[IO.FileMode]::OpenOrCreate, [IO.FileAccess]::Write, [IO.FileShare]::ReadWrite)
for ($i = 0; $i -lt 100; $i++) {
$t = [Text.Encoding]::ASCII.GetBytes("$i $(Get-Random)`r`n")
$fs.Write($t, 0, $t.Length); $fs.Flush()
Sleep 3
}
$fs.Close()
After that I ran the command on top and all the log files are cleared