In continuation of part-2 of my article on same topic we will discuss some more autolisp functions and there use here.
Reading and appending files: See the following example:
(setq f(open “aaa.txt” “r”))
This statement will open the file called aaa.txt for reading
(read-line f )
As we already written the first line as “I love you”, this statement will return that line.
(close f)
This will close the file.
Appending is very similar to writing except the fact that for appending the file need to be exist already and for writing if the file does not exist already autolisp will create it at its installation directory (most of the cases at “C:\Program Files\ACAD2000”)
(setq f(open “aaa.txt” “a”))
This statement will open the file called aaa.txt for appending.
(write-line ”addition of line” f )
As we already written the first line as “I love you”, this statement add the “addition of line “to the file.
(close f)
This will close the file.
Now in the above example if we could have opened it for writing instead of appending, then the existing text would have been overwritten by the newly added text.
Let us consider the following example:
(setq f (open “aaa.txt” “w”))
(write-line “I love u” f)
(close f)
If you have a file named aaa.txt at any location (say at “C:\MAIN DATA\aaa.txt” )other than your AutoCAD installation location (say, “C:\program files”), then the above program will not take the file which is have at “C:\MAIN DATA” instead it will create a file named “aaa.txt” at , “C:\program files” and start writing in it. To avoid this we can modify the above code as below:
(setq file (findfile "aaa.txt"))
(setq f (open file "a"))
(write-line "I love u" file)
(close file)
In this case it will first find out where in computer the file named “aaa.txt” is already there and then start operation on it.