FileReplace()

Auto Hotkey

FileReplace

Deletes the file and writes text to the file after creating it.

OutputVar := FileReplace(Text, Filename , Encoding)
Command  Example: FileReplace "text",A_ScriptDir "\MyFile.txt"
Function Example: Success := FileReplace("text",A_ScriptDir "\MyFile.txt")

Parameters

OutputVar

The name of the variable in which to store true if file was replaced or false otherwise.

Text

The text to append to the file. This text may include linefeed characters (`n) to start new lines. In addition, a single long line can be broken up into several shorter ones by means of a continuation section.

If Text is blank, Filename will be created as an empty file (but if the file already exists, its modification time will be updated).

If Text is %ClipboardAll% or a variable that was previously assigned the value of ClipboardAll, Filename will be unconditionally overwritten with the entire contents of the clipboard (i.e. FileDelete is not necessary).

Filename

The name of the file to be appended, which is assumed to be in %A_WorkingDir% if an absolute path isn't specified.

Binary mode: To append in binary mode rather than text mode, prepend an asterisk to the filename. This causes each linefeed character (`n) to be written as as a single linefeed (LF) rather than the Windows standard of CR+LF. For example: *C:\My Unix File.txt.

Encoding

Overrides the default encoding set by FileEncoding, where Encoding follows the same format.

ErrorLevel

ErrorLevel is set to 1 if there was a problem or 0 otherwise.

A_LastError is set to the result of the operating system's GetLastError() function.

Remarks

The target file is automatically closed after the text is appended (except when FileAppend is used in its single-parameter mode inside a file-reading/writing loop).

FileOpen in append mode provides more control than FileAppend and allows the file to be kept open rather than opening and closing it each time. Once a file is opened in append mode, use file.Write(string) to append the string. File objects also support binary I/O via RawWrite/RawRead or WriteNum/ReadNum, whereas FileAppend supports only text.

Related

FileOpen/File Object, FileRead, FileAppend, file-reading loop, IniWrite, FileDelete, OutputDebug, continuation sections

Example

FileAppend, Another line.`n, C:\My Documents\Test.txt

; The following example uses a continuation section to enhance readability and maintainability:
FileAppend,
(
A line of text.
By default, the hard carriage return (Enter) between the previous line and this one will be written to the file.
    This line is indented with a tab; by default, that tab will also be written to the file.
Variable references such as %Var% are expanded by default.
), C:\My File.txt

 

FileReplace(var,A_ScriptDir "\MyFile.txt")