...

View Full Version : Spaces Added When Writing to File



thesmart1
08-06-2007, 03:55 AM
I have a script that reads two numbers (separated by a comma) from a txt file and adds one to one or both of the numbers. It then writes the new numbers back to the file, in the original format.

It works, however, it keeps adding spaces to the beginning of the file. Normally this wouldn't be a major problem, but this file will eventually be modified a lot of times. That could eventually make the file size huge, slowing down the script.

Here is the script (there's more to the PHP file, but this is what I'm having trouble with):

// OPEN AND READ THE FILE
$stats_file=fopen($stats_file_name,'r+');
$stats=trim(fread($stats_file,filesize($stats_file_name)));

// PARSE AND ADD 1 WHERE APPROPRIATE
$stats_values=explode(',',$stats);
$stats_values[0]++;
if ($is_unique==true){
$stats_values[1]++;
}

// WRITE NEW STATS TO FILE
$new_stats=trim($stats_values[0].','.$stats_values[1]);
$new_stats=str_replace(' ','',$new_stats);
ftruncate($stats_file,0);
fwrite($stats_file,$new_stats);
fclose($stats_file);

The Reverend
08-06-2007, 04:38 AM
I've made scripts before involving such things, make use of the trim() function before you write to the file, that should solve your issue.

thesmart1
08-06-2007, 04:54 AM
$stats=trim(fread($stats_file,filesize($stats_file_name)));

$new_stats=trim($stats_values[0].','.$stats_values[1]);
$new_stats=str_replace(' ','',$new_stats);

I used trim in both reading and writing. I even used str_replace to try to remove spaces manually in writing to the file.

tansoft
08-06-2007, 05:57 AM
check for new line character and start of line ......

thesmart1
08-06-2007, 05:11 PM
I added $new_stats=str_replace("\n",'',$new_stats); and still got the same result.

FishMonger
08-06-2007, 06:22 PM
You need to seek to the beginning of the file after the truncate.


// OPEN AND READ THE FILE
$stats_file=fopen($stats_file_name,'r+');
$stats=trim(fread($stats_file,filesize($stats_file_name)));

// PARSE AND ADD 1 WHERE APPROPRIATE
$stats_values=explode(',',$stats);
$stats_values[0]++;
if ($is_unique==true){
$stats_values[1]++;
}

// WRITE NEW STATS TO FILE
$new_stats=$stats_values[0].','.$stats_values[1];
ftruncate($stats_file,0);
fseek($stats_file,0);
fwrite($stats_file,$new_stats);
fclose($stats_file);

FishMonger
08-06-2007, 06:25 PM
Actually, the seek can be either before or after the truncate.

thesmart1
08-06-2007, 06:42 PM
Awesome, it worked! Thanks!

FishMonger
08-06-2007, 06:59 PM
I probably should correct my last statement. Given the small test I did, it didn't matter if the seek was before or after the truncate, but in actuality, it should be done prior to the truncate.

thesmart1
08-06-2007, 08:40 PM
It works before or after, but I do now have it before ftruncate.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum