LabVIEW

cancel
Showing results for 
Search instead for 
Did you mean: 

write into existing file with "write to text file"

Hi all,
 I have a text file that contains several lines of data (text). Now I would like to replace the first three lines with text coming from a string array.

My approach is shown in WriteToFile.vi that is attached.

When I am executing this vi (with an empty file), everything seems to be working fine in the first place.
The file will contain the following text:
oneoneone
twotwotwo
threethreethree

Now, when the third element in the array is shortened (lets say to "threethr") before execution,  the file will contain  the following text:
(the file was not emptied before execution)
oneoneone
twotwotwo
threethr
three


How can I avoid the last line being written? I have made many tests and I could not find a solution.

One more example:
Lets say we have an existing file, inside this file is:
oneoneone
twotwotwo
three
fourfourfour

Now I would like to overwrite line three with "threethreethree". Therefore I execute my vi as shown in the attachment.
What I get as a result is:
oneoneone
twotwotwo
threethreethree
ur

So, the text in line four, which should not be touched, is "ur" instead of "fourfourfour".


Any idea to solve this problem?
What I basically need is replacing a line of a text file in a conveinient way.

Thanks,

Holger

----
LV 8.5.1

Download All
0 Kudos
Message 1 of 2
(2,077 Views)
The remaining fourth line is there because the third line has a <nl> at the end. You have not emptied the file so the rest of the file will be kept. This is because your line is shorter.
 
In the scond example the third line is longer and it will overwrite the beginning of the fourth line.
 
Files aren't organized in lines they are oganized in bytes. And what you write are bytes to the file even with text files.
 
Replacing a single line in a file is done by reading the file line by line. All unchanged lines are written to a temporary file and the line with the new text will be written instead of the original line to the temporary file. When the writting is done rename the original file, then rename the new file into the original file and then delete the renamed original file.
 
 
Waldemar

Using 7.1.1, 8.5.1, 8.6.1, 2009 on XP and RT
Don't forget to give Kudos to good answers and/or questions
0 Kudos
Message 2 of 2
(2,070 Views)