Sunday 13 July 2008

Batch programming tip#08: Reading from a file

Reading from file can sometimes be really useful. For example, you could imagine one process was to output lots of file names to a given file (let's call it file1.txt) and then that our batch would jump in there and retrieve those file names and print up whatever is in them (obviously in a real-world case scenario, you would want to handle the files and do something with them, e.g. archive them to a different location or whatever).

To read content from a file, we set a variable using /P and the < sign after the usual = sign.

The following code does this.

@echo off

:init_vars
set /P file_content=<file1.txt
goto action

:action
echo File content: %file_content%
goto eof

:eof
echo Press any key to close window...
pause > nul
goto blackhole

:blackhole

Note that if file1.txt doesn't exist an error message will show and the variable %file_content% will be empty.

Hey presto, we got something out of the file. This is great... except: we are only getting hold of the first line.

In the two following posts, I will explain the loop construct and how to use it to read all the lines from the file.

Thoughts in the meantime?

No comments:

Online Marketing
Add blog to our blog directory blog search directory Blog Directory Blogarama - The Blog Directory