Post by Azan on Apr 2, 2005 17:45:06 GMT -5
Saving to a Text File
In this tutorial you will learn how to ...
~ Save strings to a text file
Ok in this tutorial we wont be going to far indepth into opening/saving data files, we will just be looking into how to save something to a text file, ok first of all you are going to need a text file name it scores (just use notepad to make it) then save this file into the folder where our program will be. now I will show you how to take a simple guessing game and turn it into a guessing game that will save the history of it. Now I will be showing our entire program (as it is a really small one)
x=0
win=0
SeedRnd MilliSecs()
n=Rand(100)
name$=Input("Whats your name? ")
While Not KeyHit(1)
x=x+1
guess=Input("guess: ")
If guess<n Then Print "Too low"
If guess>n Then Print "Too high"
If guess=n Then Print "You got it it took you "+x+" guesses" win=win+1
If win=1 Then
fileout = OpenFile("scores.txt")
While Not Eof(fileout)
ReadLine(fileout)
Wend
WriteLine( fileout, "Name: "+name$+" Score: "+x)
CloseFile( fileout )
EndIf
Wend
Now most of this stuff should be basic knowledge to you (other wise please look at the other tutorials) but 1st lets look at this at the top of our program.
name$=Input("Whats your name? ")
As you can see after name we have a $ sign this is telling our program that its a string. Now lets take a look at this If statement.
If win=1 Then
fileout = OpenFile("scores.txt")
While Not Eof(fileout)
ReadLine(fileout)
Wend
WriteLine( fileout, "Name: "+name$+" Score: "+x)
CloseFile( fileout )
EndIf
Ok as you can see this will run when the player has won, but as you can see we load our txt file we made earlier, but lets look at this.
While Not Eof(fileout)
ReadLine(fileout)
Wend
This is telling our program to goto the very bottom line so we can continuosly add text without it overlapping. Now lets move on.
WriteLine( fileout, "Name: "+name$+" Score: "+x)
This is telling our program to write a line with the following information, now run the program a couple of times then take a look at the txt file (note you will need to close/reopen the txt file for the changes to take place) in my next tutorial we will learn how to encript files, and read lines not just write them as this tutorial will not help you to make a highscore table or anything it is the start of one.
If you have any questions regarding what was discussed in this tutorial please post it in this thread.
Copyright: This document may not be posted anywhere else but ragnarokcom.proboards33.com with out the authors consent, by posting anywhere else with out the authors consent you are agreeing to give me your soul mwahahaha (but feel free to post links to this site/tutorial on other sites).