Search code examples
batch-fileruntime-error

Receiving error after trying to find and load information from a file in Batch


I've been doing some experimentation in batch and I'm currently working on the beginnings of a small text adventure, but when I was testing a savegame, the program returned the error "The system cannot find the file specified." Can somebody help me out? (If its any help I'm on a school computer).

Here's the snippet of my code in question:

pushd \\schoolname\MyName$\My Documents\Discount Zork
popd

< savegame.sav (    
  set /p timesPlayed
)

Any help would be appreciated greatly. Thanks in advance!


Solution

  • I'm assuming that your intention will be to retrieve more than one value from your savegame.sav file, so perhaps changing your methodology from the outset would serve you well.

    The first advice I'd provide is to always, prefix your in game variables with the same character. (In the example below, I've chosen {, and to improve the look, I've also suffixed them with }, which is optional)

    To make sure that variables prefixed with that character, and already existing in the local environment, do not interfere with our game variables, we first of all disable them.

    Now we create three labelled sections for showing all variables with their values, saving all variables to a file, and loading all variables from that file.

    We can then call those labels as needed.

    Here's a vary basic example to show them working:

    @Echo Off
    SetLocal EnableExtensions DisableDelayedExpansion
    
    Rem Changing the current working directory, and pushing the previous to stack
    PushD "\\schoolname\MyName$\My Documents\Discount Zork" 2> NUL || GoTo :EOF
    
    Rem Disabling any predefined local variables beginning with {
    For /F "Delims==" %%G In ('"(Set {) 2> NUL"') Do Set "%%G="
    
    Rem Simulating first gameplay values for demonstration
    Set /A {timesplayed}=3,{health}=80,{strength}=126,{defence}=76,{attack}=57
    
    Rem showing values
    Call :ShowVals
    
    Rem saving values to file
    Call :SaveVals
    
    Rem zeroing variables for demostration
    Set /A {timesplayed}={health}={strength}={defence}={attack}=0
    
    Rem showing new values
    Call :ShowVals
    
    Rem loading saved values back into game
    Call :LoadVals
    
    Rem proving reloaded values
    Call :ShowVals
    
    Rem Returning to previous working directory from stack, and ending script
    PopD
    GoTo :EOF
    
    :ShowVals
    Set {
    %SystemRoot%\System32\timeout.exe /T 7 1> NUL
    Exit /B
    
    :SaveVals
    ((Set {) 2> NUL) 1> "savegame.sav"
    Exit /B
    
    :LoadVals
    For /F "UseBackQ Delims=" %%G In ("savegame.sav") Do Set "%%G"
    Exit /B