Results 1 to 10 of 40

Thread: File handling

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Brigadier General
    Join Date
    Oct 2012
    Posts
    994
    Thanks
    20
    Thanked 588 Times in 388 Posts
    Ok, I found out what the problem is - once a file has been created using the "write" function, it wont update. So, you are fine entering data into file the very first time. After that, it simply doesn't update any more. So, you have to use the "append" function, and read the data back from that basis.

    Here is what I have:

    Code:
    onPlayerConnect()
    {
    	// initialize the player kills flag
    	if( getPlayerKills() )
    		self.pers["kills"] = self.kills;
    	else
    		self.pers["kills"] = 0;
    }
    
    onPlayerKilled()
    {
    	attacker.pers["score"]++;
    	attacker.score = attacker.pers["score"];
    	// update the player kills flag along with player score
    	attacker.pers["kills"]++;
    	// save the new player kills value
    	attacker thread saveKills();
    }
    
    saveKills()
    {
    	filename = self.name + ".txt";
    	filehandle = openfile( filename, "append" );
    	
    	if( filehandle != -1 )
    	{
    		value = "";
    		if( value != "" ) value += " ";
    		value += self.pers["kills"];
    		
    		fprintln( filehandle, value );
    		closefile( filehandle );
    	}
    }
    
    getPlayerKills()
    {
    	filename = self.name + ".txt";
    	file = OpenFile( filename, "read" );
    	
    	if( file == -1 )
    		return( false );
    	
    	for( ;; )
    	{
    		elems = freadln( file );
    		
    		if( elems == -1 )
    			break;
    			
    		if( elems == 0 )
    			continue;
    	
    		line = "";
    		for( pos = 0; pos < elems; pos++ )
    		{
    			line = line + fgetarg( file, pos );
    			if( pos < elems - 1 )
    				line = line + ",";
    		}
    			
    		array = strtok( line, "," );
    		self.kills = array.size;
    	}
    	
    	CloseFile( file );
    	
    	return( true );
    }
    I was using a simple player name for the data file name, but obviously you simply replace that with a more robust player GUID name (although I would shorten the file name to the last 8 digits).

    I didn't do anything with a HUD element showing these values. I will take it that aspect of the thing can be easily created yourself.

  2. The Following 2 Users Say Thank You to Tally For This Useful Post:

    EvoloZz (10th February 2013),kung foo man (10th February 2013)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •