Search code examples
batch-filetext

How do I make a txt file editable from batch?


So right now, I am trying to figure out how to make a .txt file editable by the user of the batch program. I already have the batch file creating the file, but now I need to make it so the .txt file has what the user answered for the question. Here is what I have now:

@echo off
echo Welcome to the Space Mapping Discord Report Maker
pause
echo Made by N3ther, version 0.1 ALPHA
pause
@echo off
break>"%userdomain%\%username%\Desktop\report.txt"
echo Question 1: What is your username on Discord?`

(It's for a report maker I am moderator on.)


Solution

  • It looks like something like below is what you need:

    @echo off
    setlocal EnableExtensions EnableDelayedExpansion
    set "ReportFile=%USERPROFILE%\Desktop\report.txt"
    del "%ReportFile%" 2>nul
    
    echo Welcome to the Space Mapping Discord Report Maker
    echo(
    echo Made by N3ther, version 0.1 ALPHA
    echo(
    
    call :PromptUser 1 "What is your username on Discord?"
    call :PromptUser 2 "What is ...?"
    
    rem Restore saved environment and exit batch processing.
    endlocal
    exit /B
    
    rem This small subroutine prompts the user for an input until something is
    rem entered at all and then appends the entered input to the report file.
    
    :PromptUser
    set "Input="
    :PromptAgain
    set /P "Input=Question %~1: %~2 "
    rem Has the user entered anything at all?
    if not defined Input goto PromptAgain
    echo !Input!>>"%ReportFile%"
    goto :EOF
    

    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 /?
    • del /?
    • echo /?
    • endlocal /?
    • exit /?
    • goto /?
    • if /?
    • rem /?
    • set /?
    • setlocal /?

    Read also the Microsoft documentation about Using command redirection operators and the Wikipedia article about Windows environment variables.