Fwrite не записывает в файл
Функция идентична последовательным успешным вызовам функций fopen() , fwrite() и fclose() .
Если filename не существует, файл будет создан. Иначе, существующий файл будет перезаписан, за исключением случая, если указан флаг FILE_APPEND .
3 ответа 3
Но учтите, что если потом надо будет считывать - то считывать тоже надо будет текстово. А если используете fwrite в бинарном режиме - то потом всю структуру сразу втянете одним fread в том же бинарном режиме.
а если не затруднит, можно кусок кода как правильно применить в моем случае fread() и fwrite(). Или хотя бы ссылочку на хороший мануал, дабы разобраться. А то не очень понятно, про бинарный режим.
@V.Rotenberh Да просто fwrite - запись всего, что сказали так, как оно лежит в памяти. Числа - в их бинарном представлении и т.д. А считываете точно так же - только функцией fread, в подготовленное место (такую же структуру). Только файл должен обязательно быть открыт в бинарном режиме (c "b" в строке режима открытия) - чтобы как в памяти лежит, так и в файл шло.
тоисть при записи с помощью данных функций в любом случае, увидеть текст в файле в нормальном представлении не получится?
"Кракозябры" зависят от того просмотрщика, которым ты этот файл смотришь. Большинство из них пытаются определить кодировку автоматом. Но т. к. файл записывается не текстовый а бинарный, то вполне возможны ошибки. Если под linux, то из консоли можно посмотреть тем же mc F3. После открытия Alt+E и выбираешь ту, которая у тебя стоит - utf-8, например. Да, и лучше переключится в HEX - режим, чтобы просмотрщик не пытался интерпретировать значения из float или int как текст. :)
Кстати, имей в виду, что если кодировка у тебя utf-8 и ты используешь не ascii символы, например русские, то длинна строки в байтах может увеличится раза в 3. Так что при вводе имени из 10-15 символов можешь затереть остальные поля структуры мусором или схватить переполнение стека. :)
Да проблема проста, как швабра: бинарные данные, числа, записываются как бинарные данные. Какие еще utf-8? При чем тут они.
Автор пишет: "но на выхлопе получаю файл device.txt, а в нём сплошные крякозябры." Стало быть он открывает его каким-то текстовым просмотрщиком или редактором (расширение файла *.txt), который и показывает "крякозябры". Что вполне естественно, т. к. файл не текстовый а бинарный. Насчёт utf-8 - смотрим структуры и видим поля с типом char [. NAME_LEN] . Судя по вопросам автор не очень силён в кодировках, поэтому я и предупредил его, где могут быть проблемы с переполнением, если используется utf-8, ведь в коде никакой проверки нет.
fwrite() записывает содержимое string в файловый поток handle .
Список параметров
Указатель ( resource ) на файл, обычно создаваемый с помощью функции fopen() .
Если параметр length является целым числом ( int ), запись остановится после того, как length байтов будут записаны или будет достигнут конец строки data , смотря что произойдёт раньше.
Список параметров
Путь к записываемому файлу.
Записываемые данные. Может быть типа string , array или ресурсом потока.
Если data является потоковым ресурсом ( stream ), оставшийся буфер этого потока будет скопирован в указанный файл. Это похоже на использование функции stream_copy_to_stream() .
Также вы можете передать одномерный массив в качестве параметра data . Это будет эквивалентно вызову file_put_contents($filename, implode('', $array)) .
Значением параметра flags может быть любая комбинация следующих флагов, соединённых бинарным оператором ИЛИ ( | ).
Флаг | Описание |
---|---|
FILE_USE_INCLUDE_PATH | Ищет filename в подключаемых директориях. Подробнее смотрите директиву include_path. |
FILE_APPEND | Если файл filename уже существует, данные будут дописаны в конец файла вместо того, чтобы его перезаписать. |
LOCK_EX | Получить эксклюзивную блокировку на файл на время записи. Другими словами, между вызовами fopen() и fwrite() произойдёт вызов функции flock() . Это не одно и то же, что вызов fopen() с флагом "x". |
Корректный ресурс контекста, созданный с помощью функции stream_context_create() .
Changelog
Notes
Note:
Writing to a network stream may end before the whole string is written. Return value of fwrite() may be checked:
function fwrite_stream ( $fp , $string ) for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) $fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) return $written ;
>
>
return $written ;
>
?>?php
Note:
On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.
Note:
If stream was fopen() ed in append mode, fwrite() s are atomic (unless the size of data exceeds the filesystem's block size, on some platforms, and as long as the file is on a local filesystem). That is, there is no need to flock() a resource before calling fwrite() ; all of the data will be written without interruption.
Note:
If writing twice to the file pointer, then the data will be appended to the end of the file content:
$fp = fopen ( 'data.txt' , 'w' );
fwrite ( $fp , '1' );
fwrite ( $fp , '23' );
fclose ( $fp );
// the content of 'data.txt' is now 123 and not 23!
?>
Примечания
Замечание: Эта функция безопасна для обработки данных в двоичной форме.
Для этой функции вы можете использовать URL в качестве имени файла, если была включена опция fopen wrappers. Смотрите более подробную информацию об определении имени файла в описании функции fopen() . Смотрите также список поддерживаемых обёрток URL, их возможности, замечания по использованию и список предопределённых констант в разделе Поддерживаемые протоколы и обёртки.
Примеры
$file = 'people.txt' ;
// Открываем файл для получения существующего содержимого
$current = file_get_contents ( $file );
// Добавляем нового человека в файл
$current .= "John Smith\n" ;
// Пишем содержимое обратно в файл
file_put_contents ( $file , $current );
?>?php
$file = 'people.txt' ;
// Новый человек, которого нужно добавить в файл
$person = "John Smith\n" ;
// Пишем содержимое в файл,
// используя флаг FILE_APPEND для дописывания содержимого в конец файла
// и флаг LOCK_EX для предотвращения записи данного файла кем-нибудь другим в данное время
file_put_contents ( $file , $person , FILE_APPEND | LOCK_EX );
?>?php
Возвращаемые значения
fwrite() возвращает количество записанных байт или FALSE в случае ошибки.
Смотрите также
- fread() - Бинарно-безопасное чтение файла
- fopen() - Открывает файл или URL
- fsockopen() - Открывает соединение с интернет-сокетом или доменным сокетом Unix
- popen() - Открывает файловый указатель процесса
- file_get_contents() - Читает содержимое файла в строку
- pack() - Упаковать данные в бинарную строку
Список параметров
Указатель ( resource ) на файл, обычно создаваемый с помощью функции fopen() .
Если передан аргумент length , запись остановится после того, как length байтов будут записаны или будет достигнут конец строки string , смотря что произойдёт первым.
Учтите, что если указан аргумент length , то директива magic_quotes_runtime будет проигнорирована и строка string не будет очищена от слешей.
See Also
- fread() - Binary-safe file read
- fopen() - Opens file or URL
- fsockopen() - Open Internet or Unix domain socket connection
- popen() - Opens process file pointer
- file_get_contents() - Reads entire file into a string
- pack() - Pack data into binary string
User Contributed Notes 33 notes
After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php's fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0.
Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost.
This means the example fwrite_stream() code from the docs, as well as all the "helper" functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries.
Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure.
// BROKEN function - infinite loop when fwrite() returns 0s
function fwrite_stream ( $fp , $string ) <
for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) <
$fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) <
return $written ;
>
>
return $written ;
>
?>
if you need a function that writes all data, maybe try
/**
* writes all data or throws
*
* @param mixed $handle
* @param string $data
* @throws \RuntimeException when fwrite returned * @return void
*/
/*private static*/ function fwrite_all ( $handle , string $data ): void
$original_len = strlen ( $data );
if ( $original_len > 0 ) $len = $original_len ;
$written_total = 0 ;
for (;;) $written_now = fwrite ( $handle , $data );
if ( $written_now === $len ) return;
>
if ( $written_now < 1 ) throw new \ RuntimeException ( "could only write < $written_total >/ < $original_len >bytes!" );
>
$written_total += $written_now ;
$data = substr ( $data , $written_now );
$len -= $written_now ;
// assert($len > 0);
// assert($len === strlen($data));
>
>
>
fwrite() writes the contents of data to the file stream pointed to by stream .
Список параметров
Путь к записываемому файлу.
Записываемые данные. Может быть типа string , array или ресурсом потока.
Если data является потоковым ресурсом ( stream ), оставшийся буфер этого потока будет скопирован в указанный файл. Это похоже на использование функции stream_copy_to_stream() .
Также вы можете передать одномерный массив в качестве параметра data . Это будет эквивалентно вызову file_put_contents($filename, implode('', $array)) .
Значением параметра flags может быть любая комбинация следующих флагов, соединённых бинарным оператором ИЛИ ( | ).
Флаг | Описание |
---|---|
FILE_USE_INCLUDE_PATH | Ищет filename в подключаемых директориях. Подробнее смотрите директиву include_path. |
FILE_APPEND | Если файл filename уже существует, данные будут дописаны в конец файла вместо того, чтобы его перезаписать. |
LOCK_EX | Получить эксклюзивную блокировку на файл на время записи. Другими словами, между вызовами fopen() и fwrite() произойдёт вызов функции flock() . Это не одно и то же, что вызов fopen() с флагом "x". |
Корректный ресурс контекста, созданный с помощью функции stream_context_create() .
Список изменений
Версия | Описание |
---|---|
8.0.0 | Параметр length теперь допускает значение null . |
Возвращаемые значения
Функция возвращает количество записанных байт в файл, или false в случае возникновения ошибки.
Эта функция может возвращать как логическое значение false , так и значение не типа boolean, которое приводится к false . За более подробной информацией обратитесь к разделу Булев тип. Используйте оператор === для проверки значения, возвращаемого этой функцией.
Return Values
fwrite() returns the number of bytes written, or false on error.
Примечания
Замечание:
Запись в сетевой поток может прекратиться до того, как будут записаны все данные. Это можно контролировать с помощью проверки возвращаемого значения функции fwrite() :
function fwrite_stream ( $fp , $string ) for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) $fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) return $written ;
>
>
return $written ;
>
?>?php
Замечание:
В системах, различающих двоичные и текстовые файлы (к примеру, Windows), файл должен быть открыт используя флаг 'b' в конце аргумента mode функции fopen() .
Замечание:
Если дескриптор stream был открыт функцией fopen() в режиме "добавление в конец", то вызовы fwrite() будут атомарными (за исключением случая, если размер data превысит размер блока файловой системы, на некоторых платформах, и пока файл хранится на локальной файловой системе). То есть нет необходимости блокировать ресурс с помощью flock() перед вызовом fwrite() , и все данные будут записаны без прерываний.
Замечание:
При повторной записи в файловый указатель, данные будут добавлены в конец содержимого файла:
$fp = fopen ( 'data.txt' , 'w' );
fwrite ( $fp , '1' );
fwrite ( $fp , '23' );
fclose ( $fp );
// содержимое 'data.txt' теперь 123, а не 23!
?>
Examples
$filename = 'test.txt' ;
$somecontent = "Add this to the file\n" ;
// Let's make sure the file exists and is writable first.
if ( is_writable ( $filename ))
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
if (! $fp = fopen ( $filename , 'a' )) echo "Cannot open file ( $filename )" ;
exit;
>
// Write $somecontent to our opened file.
if ( fwrite ( $fp , $somecontent ) === FALSE ) echo "Cannot write to file ( $filename )" ;
exit;
>
echo "Success, wrote ( $somecontent ) to file ( $filename )" ;
> else echo "The file $filename is not writable" ;
>
?>
Смотрите также
- fopen() - Открывает файл или URL
- fwrite() - Бинарно-безопасная запись в файл
- file_get_contents() - Читает содержимое файла в строку
- stream_context_create() - Создаёт контекст потока
Parameters
A file system pointer resource that is typically created using fopen() .
The string that is to be written.
If length is an int , writing will stop after length bytes have been written or the end of data is reached, whichever comes first.
User Contributed Notes 37 notes
File put contents fails if you try to put a file in a directory that doesn't exist. This creates the directory.
function file_force_contents ( $dir , $contents ) $parts = explode ( '/' , $dir );
$file = array_pop ( $parts );
$dir = '' ;
foreach( $parts as $part )
if(! is_dir ( $dir .= "/ $part " )) mkdir ( $dir );
file_put_contents ( " $dir / $file " , $contents );
>
?>
It should be obvious that this should only be used if you're making one write, if you are writing multiple times to the same file you should handle it yourself with fopen and fwrite, the fclose when you are done writing.
file_put_contents() for 1,000,000 writes - average of 3 benchmarks:
real 0m3.932s
user 0m2.487s
sys 0m1.437s
fopen() fwrite() for 1,000,000 writes, fclose() - average of 3 benchmarks:
real 0m2.265s
user 0m1.819s
sys 0m0.445s
function file_force_contents ( $fullPath , $contents , $flags = 0 ) $parts = explode ( '/' , $fullPath );
array_pop ( $parts );
$dir = implode ( '/' , $parts );
if( ! is_dir ( $dir ) )
mkdir ( $dir , 0777 , true );
file_put_contents ( $fullPath , $contents , $flags );
>
file_force_contents ( ROOT . '/newpath/file.txt' , 'message' , LOCK_EX );
?>
Please note that when saving using an FTP host, an additional stream context must be passed through telling PHP to overwrite the file.
/* set the FTP hostname */
$user = "test" ;
$pass = "myFTP" ;
$host = "example.com" ;
$file = "test.txt" ;
$hostname = $user . ":" . $pass . "@" . $host . "/" . $file ;
/* the file content */
$content = "this is just a test." ;
/* create a stream context telling PHP to overwrite the file */
$options = array( 'ftp' => array( 'overwrite' => true ));
$stream = stream_context_create ( $options );
/* and finally, put the contents */
file_put_contents ( $hostname , $content , 0 , $stream );
?>
It's important to understand that LOCK_EX will not prevent reading the file unless you also explicitly acquire a read lock (shared locked) with the PHP 'flock' function.
i.e. in concurrent scenarios file_get_contents may return empty if you don't wrap it like this:
$myfile = fopen ( 'test.txt' , 'rt' );
flock ( $myfile , LOCK_SH );
$read = file_get_contents ( 'test.txt' );
fclose ( $myfile );
?>
If you have code that does a file_get_contents on a file, changes the string, then re-saves using file_put_contents, you better be sure to do this correctly or your file will randomly wipe itself out.
Make sure not to corrupt anything in case of failure.
function file_put_contents_atomically ( $filename , $data , $flags = 0 , $context = null ) if ( file_put_contents ( $filename . "~" , $data , $flags , $context ) === strlen ( $contents )) return rename ( $filename . "~" , $filename , $context );
>
@ unlink ( $filename . "~" , $context );
return FALSE ;
>
This functionality is now implemented in the PEAR package PHP_Compat.
More information about using this function without upgrading your version of PHP can be found on the below link:
It's worth noting that you must make sure to use the correct path when working with this function. I was using it to help with logging in an error handler and sometimes it would work - while other times it wouldn't. In the end it was because sometimes it was called from different paths resulting in a failure to write to the log file.
__DIR__ is your friend.
File put contents fails if you try to put a file in a directory that doesn't exist. This function creates the directory.
file_force_contents ( 'test1.txt' , 'test1 content' ); // test1.txt created
file_force_contents ( 'test2/test2.txt' , 'test2 content' );
// test2/test2.txt created "test2" folder.
file_force_contents ( '~/test3/test3.txt' , 'test3 content' );
// /path/to/user/directory/test3/test3.txt created "test3" folder in user directory (check on linux "ll ~/ | grep test3").
?>
In reply to the previous note:
If you want to emulate this function in PHP4, you need to return the bytes written as well as support for arrays, flags.
I can only figure out the FILE_APPEND flag and array support. If I could figure out "resource context" and the other flags, I would include those too.
define('FILE_APPEND', 1);
function file_put_contents($n, $d, $flag = false) $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';
$f = @fopen($n, $mode);
if ($f === false) return 0;
> else if (is_array($d)) $d = implode($d);
$bytes_written = fwrite($f, $d);
fclose($f);
return $bytes_written;
>
>
A more simplified version of the method that creates subdirectories:
function path_put_contents($filePath, $contents, $flags = 0)
if (! is_dir($dir = implode('/', explode('/', $filePath, -1))))
mkdir($dir, 0777, true);
file_put_contents($filePath, $contents, $flags);
>
To upload file from your localhost to any FTP server.
pease note 'ftp_chdir' has been used instead of putting direct remote file path. in ftp_put . remoth file should be only file name
$host = '*****' ;
$usr = '*****' ;
$pwd = '**********' ;
$local_file = './orderXML/order200.xml' ;
$ftp_path = 'order200.xml' ;
$conn_id = ftp_connect ( $host , 21 ) or die ( "Cannot connect to host" );
ftp_pasv ( $resource , true );
ftp_login ( $conn_id , $usr , $pwd ) or die( "Cannot login" );
// perform file upload
ftp_chdir ( $conn_id , '/public_html/abc/' );
$upload = ftp_put ( $conn_id , $ftp_path , $local_file , FTP_ASCII );
if( $upload ) < $ftpsucc = 1 ; >else < $ftpsucc = 0 ; >
// check upload status:
print (! $upload ) ? 'Cannot upload' : 'Upload complete' ;
print "\n" ;
// close the FTP stream
ftp_close ( $conn_id );
?>
I'm updating a function that was posted, as it would fail if there was no directory. It also returns the final value so you can determine if the actual file was written.
public static function file_force_contents($dir, $contents) $parts = explode('/', $dir);
$file = array_pop($parts);
$dir = '';
foreach($parts as $part) if (! is_dir($dir .= "/")) mkdir($dir);
>
return file_put_contents("", $contents);
>
I suggest to expand file_force_contents() function of TrentTompkins at gmail dot com by adding verification if patch is like: "../foo/bar/file"
if (strpos($dir, "../") === 0)
$dir = str_replace("..", substr(__DIR__, 0, strrpos(__DIR__, "/")), $dir);
file_put_contents does not issue an error message if file name is incorrect(for example has improper symbols on the end of it /n,/t)
that is why use trim() for file name.
$name=trim($name);
file_put_contents($name,$content);
I had some troubles using file_put_contents with an absolute but no canonicalized path (eg. w:/htdocs/pri/../test/log.txt): on windows environment php was unable to create the file also using the realpath function .
I had to use fopen and frwite functions to write the data.
I wrote this script implementing the file_put_contents() and file_get_contents() functions to be compatible with both php4.* and php 5.*. It is a PHP Command line interface script which searches and replaces a specific word recursively through all files in the supplied directory hierarchy.
Usage from a Linux command line: ./scriptname specifieddirectory searchString replaceString
if( $argc != 4 )
echo "This command replaces a search string with a replacement string\n for the contents of all files in a directory hierachy\n" ;
echo "command usage: $argv [ 0 ] directory searchString replaceString\n" ;
echo "\n" ;
exit;
>
?>
if (! function_exists ( 'file_put_contents' )) function file_put_contents ( $filename , $data ) $f = @ fopen ( $filename , 'w' );
if (! $f ) return false ;
> else $bytes = fwrite ( $f , $data );
fclose ( $f );
return $bytes ;
>
>
>
function get_file_contents ( $filename )
/* Returns the contents of file name passed
*/
if (! function_exists ( 'file_get_contents' ))
$fhandle = fopen ( $filename , "r" );
$fcontents = fread ( $fhandle , filesize ( $filename ));
fclose ( $fhandle );
>
else
$fcontents = file_get_contents ( $filename );
>
return $fcontents ;
>
?>
function openFileSearchAndReplace ( $parentDirectory , $searchFor , $replaceWith )
//echo "debug here- line 1a\n";
//echo "$parentDirectory\n";
//echo "$searchFor\n";
//echo "$replaceWith\n";
if ( $handle = opendir ( " $parentDirectory " )) while ( false !== ( $file = readdir ( $handle ))) if (( $file != "." && $file != ".." ) && ! is_dir ( $file )) chdir ( " $parentDirectory " ); //to make sure you are always in right directory
// echo "$file\n";
$holdcontents = file_get_contents ( $file );
$holdcontents2 = str_replace ( $searchFor , $replaceWith , $holdcontents );
file_put_contents ( $file , $holdcontents2 );
// echo "debug here- line 1\n";
// echo "$file\n";
>
if( is_dir ( $file ) && ( $file != "." && $file != ".." ))
$holdpwd = getcwd ();
//echo "holdpwd = $holdpwd \n";
$newdir = " $holdpwd " . "/ $file " ;
//echo "newdir = $newdir \n"; //for recursive call
openFileSearchAndReplace ( $newdir , $searchFor , $replaceWith );
//echo "debug here- line 2\n";
//echo "$file\n";
>
>
closedir ( $handle );
>
>
$parentDirectory2 = $argv [ 1 ];
$searchFor2 = $argv [ 2 ];
$replaceWith2 = $argv [ 3 ];
//Please do not edit below to keep the rights to this script
//Free license, if contents below this line is not edited
echo "REPLACED\n' $searchFor2 ' with ' $replaceWith2 ' recursively through directory listed below\nFor all files that current user has write permissions for\nDIRECTORY: ' $parentDirectory2 '\n" ;
echo "command written by Kolapo Akande :) all rights reserved :)\n" ;
$holdpwd = getcwd ();
//echo "$holdpwd\n";
chdir ( $parentDirectory2 );
openFileSearchAndReplace ( $parentDirectory2 , $searchFor2 , $replaceWith2 );
exit;
?>
User Contributed Notes 33 notes
After having problems with fwrite() returning 0 in cases where one would fully expect a return value of false, I took a look at the source code for php's fwrite() itself. The function will only return false if you pass in invalid arguments. Any other error, just as a broken pipe or closed connection, will result in a return value of less than strlen($string), in most cases 0.
Therefore, looping with repeated calls to fwrite() until the sum of number of bytes written equals the strlen() of the full value or expecting false on error will result in an infinite loop if the connection is lost.
This means the example fwrite_stream() code from the docs, as well as all the "helper" functions posted by others in the comments are all broken. You *must* check for a return value of 0 and either abort immediately or track a maximum number of retries.
Below is the example from the docs. This code is BAD, as a broken pipe will result in fwrite() infinitely looping with a return value of 0. Since the loop only breaks if fwrite() returns false or successfully writes all bytes, an infinite loop will occur on failure.
// BROKEN function - infinite loop when fwrite() returns 0s
function fwrite_stream ( $fp , $string ) <
for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) <
$fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) <
return $written ;
>
>
return $written ;
>
?>
if you need a function that writes all data, maybe try
/**
* writes all data or throws
*
* @param mixed $handle
* @param string $data
* @throws \RuntimeException when fwrite returned * @return void
*/
/*private static*/ function fwrite_all ( $handle , string $data ): void
$original_len = strlen ( $data );
if ( $original_len > 0 ) $len = $original_len ;
$written_total = 0 ;
for (;;) $written_now = fwrite ( $handle , $data );
if ( $written_now === $len ) return;
>
if ( $written_now < 1 ) throw new \ RuntimeException ( "could only write < $written_total >/ < $original_len >bytes!" );
>
$written_total += $written_now ;
$data = substr ( $data , $written_now );
$len -= $written_now ;
// assert($len > 0);
// assert($len === strlen($data));
>
>
>
Примеры
$filename = 'test.txt' ;
$somecontent = "Добавить это к файлу\n" ;
// Вначале давайте убедимся, что файл существует и доступен для записи.
if ( is_writable ( $filename ))
// В нашем примере мы открываем $filename в режиме "записи в конец".
// Таким образом, смещение установлено в конец файла и
// наш $somecontent допишется в конец при использовании fwrite().
if (! $fp = fopen ( $filename , 'a' )) echo "Не могу открыть файл ( $filename )" ;
exit;
>
// Записываем $somecontent в наш открытый файл.
if ( fwrite ( $fp , $somecontent ) === FALSE ) echo "Не могу произвести запись в файл ( $filename )" ;
exit;
>
echo "Ура! Записали ( $somecontent ) в файл ( $filename )" ;
> else echo "Файл $filename недоступен для записи" ;
>
?>
Примеры
$filename = 'test.txt' ;
$somecontent = "Добавить это к файлу\n" ;
// Вначале давайте убедимся, что файл существует и доступен для записи.
if ( is_writable ( $filename ))
// В нашем примере мы открываем $filename в режиме "записи в конец".
// Таким образом, смещение установлено в конец файла и
// наш $somecontent допишется в конец при использовании fwrite().
if (! $handle = fopen ( $filename , 'a' )) echo "Не могу открыть файл ( $filename )" ;
exit;
>
// Записываем $somecontent в наш открытый файл.
if ( fwrite ( $handle , $somecontent ) === FALSE ) echo "Не могу произвести запись в файл ( $filename )" ;
exit;
>
fwrite() записывает содержимое data в файловый поток stream .
Примечания
Замечание:
Запись в сетевой поток может прекратиться до того, как будут записаны все данные. Это можно контролировать с помощью проверки возвращаемого значения функции fwrite() :
function fwrite_stream ( $fp , $string ) for ( $written = 0 ; $written < strlen ( $string ); $written += $fwrite ) $fwrite = fwrite ( $fp , substr ( $string , $written ));
if ( $fwrite === false ) return $written ;
>
>
return $written ;
>
?>?php
Замечание:
В системах, различающих двоичные и текстовые файлы (к примеру, Windows), файл должен быть открыт используя флаг 'b' в конце аргумента mode функции fopen() .
Замечание:
Если дескриптор handle был открыт функцией fopen() в режиме "записи в конец", то вызовы fwrite() будут атомарными (за исключением случая, если string размер блока файловой системы, на некоторых платформах, и пока файл хранится на локальной файловой системе). Т.е. нет необходимости блокировать ресурс с помощью flock() перед вызовом fwrite() - все данные будут записаны без прерываний.
Замечание:
При повторной записи в файловый указатель данные будут добавлены в конец содержимого файла:
$fp = fopen ( 'data.txt' , 'w' );
fwrite ( $fp , '1' );
fwrite ( $fp , '23' );
fclose ( $fp );
// содержимое 'data.txt' теперь 123, а не 23!
?>
Возвращаемые значения
fwrite() возвращает количество записанных байт или false в случае возникновения ошибки.
Читайте также: