Home > other >  Read specific line of TXT file in batch [closed]
Read specific line of TXT file in batch [closed]

Time:09-17

I am making a basic game in batch for fun, and want to store the game data in a text file. I already know how to add text to my text file, and how to create text files. But I don't know how to have it read the text files. I want it to read one line at a time, that way I can have it reading one line of data at a time.

CodePudding user response:

It is pretty easy to load and save environment variables of a batch file game.

@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem If the file with saved values for the batch game exists at all,
rem read the lines with variable name and associated value and set
rem them in current execution environment.

if exist "%APPDATA%\WebsterGames\%~n0.ini" for /F "usebackq delims=" %%I in ("%APPDATA%\WebsterGames\%~n0.ini") do set "%%I"

rem Define all environment variables not defined now because of there is no
rem file with variable names and values stored from a previous execution of
rem the batch file game like on first run of the batch file by the current
rem user or some variables are missing after load from file like on batch
rem file is updated in comparison to previous execution and has now more
rem variables and values to save/load than the previous version of the game.

if not defined Health set "Health=100"
if not defined Money  set "Money=50"
if not defined Player set "Player=Colton Webster"
rem ... and so on for the other variables.

rem Here is the code for the batch file game.

rem Save all variables with their values into a subdirectory with name
rem WebsterGames in the application data directory of the current user with
rem the file name being the batch file name with file extension being .ini.

md "%APPDATA%\WebsterGames" 2>nul
if exist "%APPDATA%\WebsterGames\" (
    set Health
    set Money
    set Player
    rem ... and so on for the other variables.
)>"%APPDATA%\WebsterGames\%~n0.ini"
endlocal

The lines with command rem are remarks (comments) which can be removed in real batch file.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • call /? ... explains %~n0 ... file name of argument 0 which is the batch file name without file extension.
  • echo /?
  • endlocal /?
  • for /?
  • if /?
  • md /?
  • rem /?
  • set /?
  • setlocal /?

Read the Microsoft documentation about Using command redirection operators for an explanation of 2>nul.

  • Related