PDA

View Full Version : Parsing? a number


Saj
05-12-2003, 08:19 PM
Hi,

I'm trying to open a file called num.txt, and inside that file is a number, suppose it is 1. What I need to do is:


Open the file
Parse the number inside it so that it can numbers can be added to it
Replace the number in the file with number + 1
Close the file


I don't understand how to use the fread with the filesize and how I could "parse" (correct me if this is the wrong term) the string in the file and pretty much add 1 to it.

Thanks.

mordred
05-12-2003, 08:52 PM
// open file for reading and writing
$fp = fopen("num.txt", "rb+");

// read the first 100 bytes (~ chars) of the file
$content = fread($fp, 100);
echo $content;
// parse the integer value from the file content, base 10
$newNumber = intval($content, 10);

// reset the file pointer, so that we start writing
// at position 0
fseek($fp, 0);

// write the new number
fwrite($fp, $newNumber + 1);

// close the file
fclose($fp);


No locking of the file though... bad me.

Saj
05-12-2003, 09:55 PM
Thanks for that. I got it to work now :)

Just a couple of question:

1. What is "rb+"?
2. How could you lock the file? I don't want it to be locked, ut just wondering.

ConfusedOfLife
05-13-2003, 01:32 PM
Answering your questions:

[list=1]
r is standing for read and b means binary, that + lets you both read and write, so, you could have written wb+ that didn't have any difference with what is currently written. By the way w stands for write (you were thinking of that yourself, huh?!)
By saying locking a file, we mean that if there are simultanious processes trying to write into the file, we should stop them somehow and lock the file till the first process finishes its job and then we release the lock for the 2nd, 3rd and ... process to do their job alternatively. You can search for flock to find out more.
[/list=1]

Saj
05-13-2003, 03:16 PM
Ok that helps. Also, I meant w+, but I found that didn't work because it erased the info forst :D

Thanks for your help.