Writing to file not seems to not be working

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
phillid
Posts: 109
Joined: 03 Apr 2010 20:27
Location: Wellington, New Zealand
Contact:

Writing to file not seems to not be working

#1 Post by phillid » 04 May 2012 01:11

Hi guys. I've looked this script over thousands of times now and I haven't found the problem. I think I need a fresh pair of eyes to look at it.

As part of a program, I have a configuration section that writes some values from the user into a config file.

This code writes to the file:

Code: Select all

set /p "Alias=Name/Nickname/Alias: "
set /p "RoomDir=Room Directory/Drive: "
set /p "Rate=Refresh Rate: "
set /p "choice=Save these settings? (Y/N): "
if /i not "%Choice%"=="Y" (
   echo Changes aborted
   ping localhost -n 2 -w 1000 >nul
   goto mainmenu
)
echo Alias=%Alias%>batchat.ini
echo Rate=%Rate%>>batchat.ini
echo RoomDir=%RoomDir%>>batchat.ini


And this code reads the settings back into variables

Code: Select all

for /f "delims=" %%a in ('findstr /r /v /c:"^\[.*\]$" "batchat.ini"') do set "%%a"


Problem:
I'm pretty sure the first code snippet seems to be the problem. When I save the settings and open the config file, there's an entry for the alias and the roomdir but nothing for the rate.

Can anyone spot my mistake here?

Thanks,
Phillid

foxidrive
Expert
Posts: 6031
Joined: 10 Feb 2012 02:20

Re: Writing to file not seems to not be working

#2 Post by foxidrive » 04 May 2012 01:26

When you echo a number into a file
echo 1>file.txt
then cmd takes it as defining a steam, such as stdout (1) and stderr (2) etc.

This example redirects stderr to nul while echoing abc into the file.
echo abc>file.txt 2>nul
so you can see why the numbers are often problematic.

So the solution is to leave a space after the variable name, or to use a different method to echo the numbers.

Two methods that will allow you to echo numbers without trailing spaces

Code: Select all

>batchat.ini echo Alias=%Alias%
>>batchat.ini echo Rate=%Rate%
>>batchat.ini echo RoomDir=%RoomDir%



Code: Select all

(
echo Alias=%Alias%
echo Rate=%Rate%
echo RoomDir=%RoomDir%
)>batchat.ini

phillid
Posts: 109
Joined: 03 Apr 2010 20:27
Location: Wellington, New Zealand
Contact:

Re: Writing to file not seems to not be working

#3 Post by phillid » 05 May 2012 04:02

Of course! *facepalm* I remember using that a while ago.

Thanks for that, I got it to work perfectly!

Thanks
Phillid

Post Reply