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 gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

read in, rtrim(), write out

Status
Not open for further replies.

disord3r

Programmer
Apr 12, 2002
189
US
At some point, "^M" got written to the end of every single script I have, so I wrote up a quick script to read the contents of the directory and, file-by-file, read in the contents, rtrim the ^M off the end of each line, and write it out.

Here's the code:
---------------------

if ($dir = @opendir("source_dir"))
{
while (($file = readdir($dir)) !== false)
{
if (strstr($file, "php") or strstr($file, "bck"))
{
$fp = fopen($file, "r");
while (!feof($fp))
{
$chunk = fgets($fp, 1024);
$chunk = rtrim($chunk)."\n";
$file_complete = $file_complete.$chunk;
}

$fp2 = fopen("dest_dir/".$file, "w");
fwrite ($fp2, $file_complete);
fclose($fp2);
fclose($fp);
}
else
{
continue;
}
}
closedir($dir);
}

-----------------------

Things appear to work fine when I run it. In the destination directory (luckily, I didn't have it output to the EXACTY same directory :)), I have the exact same number of files with the exact same names as in the source directory, but with one small difference: they all have the exact same content, too. :)

For some reason, the contents of the first file processed by the script is what gets written out to each and every file processed after that, so they're all identical in essence. The thing that bugs me is that is actually names the files properly, so I know its advancing through all the loops properly, but I cant find out what causes it to use the same data over and over.

Any help is most appreciated.
 
N/M. Here's the culprit.

$file_complete = $file_complete.$chunk;

Because these are all done in one run of the script, file_complete was growing ever larger with each iteration. I noticed something was up when a 52 byte file suddenly became over 100k after the script ran! :)
 
You get a ^M at the end of every line when you view a file in say VI under unix.
This is showing you how windows(DOS actually) writes a newline character.
Under unix to reme these use the dtox command.
dtox file.php >> unix_file.php

Its alot easier to save these files as unix from a text editor such as textpad. ***************************************
Party on, dudes!
[cannon]
 
If you ftp text files to the server in ASCII mode, the conversion is done automatically as well. Sending them in binary mode is where you run into trouble.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top