Append or Prepend to a Text or Binary File in LabVIEW

Updated Dec 1, 2021

Reported In

Software

  • LabVIEW
  • LabVIEW NXG

Operating System

  • Windows

Issue Details

  • I am using the Open/Create/Replace File function to open a file. When I write to the file multiple times, the data stored in the file is being overwritten with new data on each write. How do I append data to the end of the file on each file write?
  • When I open a file then read the file first and then write to it, the new line will be appended. How do I do this without the read function?

Solution

It is possible to append a line of text at the end of a file without reading the whole text file by using the Set File Position function found on the Functions palette under Programming >> File I/O >> Advanced File Functions. This function allows you to set the cursor to either the start, the end or to a user-specified point in the file. This function should be placed between the Open/Create/Replace function and the Write Text File function or Write Binary File functions using the same refnums.   This works for both LabVIEW and LabVIEW NXG.

The resulting code should look like the one below when appending data to a text file:
 
append text to file.png

Note: Adding data at the beginning of a file or pre-pending (as opposed to appending) without reading the original file is not a supported operation. The file already has pre-allocated memory space so for a prepend to occur all the existing data would need to be shifted down in memory so you need to read all the data and re-write it. It is possible though to write at the beginning of a file by setting the position of the current file mark at the beginning of the file but this will overwrite the first bytes of it when using the write to text file function.

Additional Information

When a file is opened in LabVIEW the cursor is set to the first position in the file. When a Read Text File or Read Binary File function is used it scans the full file and subsequently moves the cursor through the file to the end and so when a write occurs after that it will do it from the end.