-
April 14th, 2008, 08:12 PM
#1
fgets the first bytes of file
Hello,
i want to downloading the first bytes of files temporary on my server to get some information of file.
The function that i am using is fopen to read the file_to_read and then the fgets to save temporary in file_to_write.txt .
Sometimes the file_to_read is very big and i get an error so i want to save the first 4096 bytes from file_to_read to file_to_write.txt .
This the code that im using
Code:
$handle = @fopen("$file_to_read", "r");
clearstatcache();
ignore_user_abort(true);
if ($handle) {
while (!feof($handle)) {
$buffer = fgets($handle, 2048);
$filename = 'file_to_write.txt';
if (is_writable($filename)) {
if (!($handle2 = fopen("$filename", "w+"))) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle2, $buffer) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
fclose($handle2);
}
}
fclose($handle);
}
any help?
-
April 15th, 2008, 06:49 AM
#2
Re: fgets the first bytes of file
The following will get you the first 4096 bytes of any file. If you want to check the size before reading it, use filesize().
PHP Code:
<?php
$path = 'example.txt';
$file = fopen($path, 'r');
$contents = fread($file, 4096);
fclose($file);
?>
If the post was helpful...Rate it! Remember to use [code] or [php] tags.
-
April 15th, 2008, 07:53 PM
#3
Re: fgets the first bytes of file
I cant understand how can i use your code!
Can you edit mine?
-
April 17th, 2008, 05:51 AM
#4
Re: fgets the first bytes of file
PHP Code:
$handle = @fopen("$file_to_read", "r"); clearstatcache(); ignore_user_abort(true); if ($handle) { $buffer = fread($handle, 4096);
$filename = 'file_to_write.txt';
if (is_writable($filename)) {
if (!($handle2 = fopen("$filename", "w+"))) { echo "Cannot open file ($filename)"; exit; }
if (fwrite($handle2, $buffer) === FALSE) { echo "Cannot write to file ($filename)"; exit; } fclose($handle2); } fclose($handle); }
The proper technique for what your doing is to use fread() instead of fgets().
I'm not sure what is in the file your trying to read, but if its binary data or plaintext thats all on one line, fgets() will take very long to execute and possibly not execute at all because it attempts to get "a line" from the file pointer. fread() just reads how many ever bytes from the beginning of the file you specify so it is not as intensive.
However fread() does not utilize the file pointer (keeping track of where it was last read/written) so it's not made for use in a loop.
Hope that helped.
-Zetas
Last edited by Zetas; April 17th, 2008 at 05:53 AM.
-
April 17th, 2008, 08:17 AM
#5
Re: fgets the first bytes of file
It works!
Thank you
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|