-1

I am making a basic game in batch for fun and I 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 the text file. But I don't know how to have it read the lines in the text file. I want it to read one line at a time, that way I can have it reading one line of data at a time.

Mofi
  • 46,139
  • 17
  • 80
  • 143
  • 2
    The `FOR` command with the `/F` option is used to read a text file. Plenty of examples on this website if you use the search facility. – Squashman Aug 28 '21 at 18:08

1 Answers1

0

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.

To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and 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.

Mofi
  • 46,139
  • 17
  • 80
  • 143