Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Reading and then writing to a specific line of a text file 1

Status
Not open for further replies.

robertd18

Technical User
Jan 14, 2003
32
US
Hi i can't figure out how to do this checked the FAQs and keyword searched no luck. The new data is submitted by a form "post". all it does is add 25 to the line[4] of the text file. thanks!
 
So what you want to do is to have your script receive user input and add 25 to whatever value is in line number 4 of a specific file?
If this is the case, then this should work:

[tt]$lines = file(&quot;<filename>&quot;); /* Read <filename> into an array, each line having it's own index */
$lines[4] = rtrim($lines[4]) + 25; /* Remove trailing newlines and add 25 to line 4 */
if (!$fp = fopen(&quot;<filename>&quot;, &quot;w&quot;)) /* Open <filename> for writing to write back the data */
die(&quot;Unable to open <filename>&quot;);
foreach ($lines as $line) /* Loop over each line */
{
fwrite($fp, $line); /* Write the line to the file */
}
fclose($fp);[/tt] //Daniel
 
Oh, and I forgot to mention this.
If you use the above code, you can have race conditions and memory problems.
The race condition would occur when two users access the file at the same time and two processes opens and writes to the file simultaneously. This would most likely corrupt the file.
With memory problems, I mean that if you have a large file, when the whole file gets read into memory (in the array), your server may run out of memory. //Daniel
 
Hi that script works ok but i am having one more problem
I am using a form to post, and it is passing a variable to the php specifying which file to put the data in. But
the script wont work; it works when i just script in the variable but it wont work when the form send the variable
thanks
 
if the variable is foo on the form, you'll need to do

$foo = $_POST[&quot;foo&quot;];

somewhere in the beginning of your script.

-Rob
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top