2

I need to count every time a computer is turn off or restarted. Thus I believe i can do this with a batch file by adding it to the start menu. Thus everytime you turn on PC it will run. When it runs it should

open c:\count.txt
read in the value on that text file
add 1 to it
write the value to the text file
exit.

but I have not used batch files much and could not figure out how to read in the number from the text file.

Glen Morse
  • 2,437
  • 8
  • 51
  • 102

2 Answers2

4

based on your idea (updating a counter in a file):

rem open c:\count.txt
rem read in the value on that text file
set /p count=<c:\count.txt
rem add 1 to it
set /a count+=1
rem write the value to the text file
>c:\count.txt echo.%count%
rem exit.
exit

Notice: Take care, that you choose a path the user has write access to. (C:\ may not work without privileges)

Stephan
  • 53,940
  • 10
  • 58
  • 91
  • Good example of "set /p" and "set /a". – zentrunix Sep 17 '13 at 12:29
  • i like this , its quick and easy for me to understand :D One question i have though is how will this work if 1. the count.txt file got deleted? would it create the file again. would it give an error cause its a blank file? would it still add 1.. I could test these out i guess. just restarting a computer , or restarting this computer is something i dont want to do due to the applications running on it. but will if you can not answer these. Thanks Glen – Glen Morse Sep 18 '13 at 03:18
  • if count.txt does not exist, `set /p` will give an error. Nevertheless, `set /a` will correctly "add" one. @foxidrive: thanks for the edit :) – Stephan Sep 18 '13 at 12:59
1

This is a solution from MS-DOS days. The c:\count.txt filesize isn't going to be an issue for any realistic number.

To reset the counter delete c:\count.txt

@echo off
>>c:\count.txt echo 1
echo Count is up to:
find /c "1" <c:\count.txt
foxidrive
  • 40,353
  • 10
  • 53
  • 68
  • I dont understand this, this will readin the count.txt and echo out first line right? not sure what >>c:\count line does or the find. – Glen Morse Sep 17 '13 at 08:00
  • Try it a few times - and examine the file. That should make it clearer. – foxidrive Sep 17 '13 at 09:18
  • LOL not elegant, but functional! @GlenMorse: every run of the batch will add a line `1` to the file. The `find` counts the `1`s (`/c`) – Stephan Sep 17 '13 at 11:50