Fopen код ошибки

������������� ������� ��������� ��������� ���������� (man-��)

fopen (3)


  • fopen (3) ( Solaris man: ������������ ������ )
  • fopen (3) ( FreeBSD man: ������������ ������ )
  • >> fopen (3) ( ������� man: ������������ ������ )
  • fopen (3) ( Linux man: ������������ ������ )
  • fopen (3) ( POSIX man: ������������ ������ )
  •  

    ��������

    fopen, fdopen, freopen — ������� ��� �������� �������
     

    ���������

    #include <stdio.h>

    FILE *fopen(const char *path, const char *mode);

    FILE *fdopen(int fildes, const char *mode);

    FILE *freopen(const char *path, const char *mode, FILE *stream);

     

    ��������

    �������
    fopen

    ��������� ���� � ������
    path

    � ��������� ��� � �������.

    ��������
    mode

    ��������� �� ������, ������������ � ����� �� ��������� �������������������
    (�� ���� ����� ��������� �������������� �������):

    r

    ������� ��������� ���� ��� ������. ������ ���������� � ������ �����.
    r+

    ������� ��� ������ � ������. ������ ��� ������ ���������� � ������ �����.
    w

    «�������» ���� �� ������� ����� ��� ������� ��������� ���� � ������� ��� ��� ������.
    ������ ���������� � ������ �����.
    w+

    ������� ��� ������ � ������. ���� ���������, ���� �� ����� ��� �� ������������,
    � ��������� ������ �� «���������». ������ ��� ������ ���������� � ������ �����.
    a

    ������� ��� ����������� (������ � ����� �����). ���� ���������, ���� �� �����
    ��� �� ������������. ������ �������������� � ����� �����.
    a+

    ������� ��� ������ � ����������� (������ � ����� �����). ���� ���������, ���� ��
    ����� ��� �� ������������. ������ ��� ������ ������������ � ����� �����.

    ������
    mode

    ����� ����� �������� � ���� ������ «b» � �������� ���������� ������� ���
    �������, ��������� � ����� ��������� ���� �������������� ����������.
    ��� ���������� �������� ������� ������ � ������, ���� ���������
    ������������� ���� ������ � ANSI X3.159-1989
    («ANSI C»); ������ «b» ������������ �� ����
    POSIX-����������� ��������, ������� Linux.
    ������ ������� ����� ����� ���������� � ��������� � �������� ������,
    � ���������� «b» ����� ��������� ��������, ���� �� ������������� ����-�����
    � �������� ����; ��������, ���� ��������� ����� �����-������ �������� �
    ��-Unix ����������.

    ����� ��������� ���� ����� ����� ��������
    S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH

    (0666), ��� ���������������� ��������� umask �������� (��.
    umask(2)).

    ������ � ������ ����� ������������� ���� �� ����� � ������, ��������
    ��� ������/������, � ����� �������. �������, ��� ANSI C �������, �����
    ����� �������/������� �������������� ������� ���������������� � �����,
    ���� �������� ����� �� �������� ����� �����. ���� ��� ������� ��
    �����������, �� ��� ������ ����������� ���������� ���������, �� �����������
    � ����� ��������� ����������. �� ���� ����� ������� ����� (� ������ �
    ������������� ����������� � Linux) ������������ �������
    fseek

    ���
    fgetpos

    ����� ���������� ������ � ������ � ����� ������. ��� �������� �����
    ���������� ���� «�������» (���, ��������, fseek(…, 0L,SEEK_CUR),
    ��������� ��� ����, ����� ������ �� �������� ������ �������������).

    �������� ����� � ������ ����������� (a � �������� ������� �������
    mode)

    �������� � ����, ��� ��� ����������� �������� ������ � ���� �����
    ������������ � ����� �����, ��� ���� �� ����� ���� ���� ������� �������

    fseek(stream,0,SEEK_END);

    �������
    fdopen

    ��������� ����� � ������������ ���������� �����
    fildes.

    �����
    mode

    ������ (���� �� ��������� ��������: «r», «r+», «w», «w+», «a», «a+»)
    ������ ���� ��������� � ������� ��������� �����.
    ��������� �������� ������� � ����� ������ ��������� ��������, ������ ��������
    fildes,

    � ��������� ������ � ����� ����� �� �������� ����� ����.
    ������ «w» ��� «w+» �� «�������» ����.
    ��������� ����� �� ���������� � ����� ������, ����� �����, ���������
    fdopen,

    �����������. ��������� ����������
    fdopen

    � ����� ������� ������ �����������.

    �������
    freopen

    ��������� ���� � ������
    path

    � ��������� ��� � �������
    stream.

    �������� ����� (���� ����� �����������) �����������. ��������
    mode

    ������������, ��� � � �������
    fopen .

    �������� ������� �������
    freopen

    �������� ��������� �����, ���������� �� ����������� ��������� �������
    (stderr, stdin, or stdout).

     

    ������������ ��������

    ��� �������� ����������
    fopen

    fdopen


    freopen

    ���������� ���������
    FILE.

    ����� ������������
    NULL,

    � � ���������� ����������
    errno

    ������������ ��� ������.
     

    ��������� ������

    EINVAL

    �����
    mode

    ����������
    fopen,

    fdopen,

    ���
    freopen

    �������� ��������.

    �������
    fopen,

    fdopen


    freopen

    ��� ������� ������������� ��������
    errno

    ������ ������-���� �������� �� ������������ �
    malloc(3).

    �������
    fopen

    ��� ������� ������������� ��������
    errno

    ������ ������-���� �������� �� ������������ �
    open(2).

    �������
    fdopen

    ��� ������� ������������� ��������
    errno

    ������ ������-���� �������� �� ������������ �
    fcntl(2).

    �������
    freopen

    ��� ������� �������������
    errno

    ������ ������-���� �������� �� ������������ �
    open(2),

    fclose(3)


    fflush(3).

     

    ������������ ����������

    �������
    fopen


    freopen

    ������������� ��������� ANSI X3.159-1989 («ANSI C»). �������
    fdopen

    ������������� ��������� IEEE Std1003.1-1988 («POSIX.1»).
     

    ��. �����

    open(2),

    fclose(3),

    fileno(3)


     

    Index

    ��������
    ���������
    ��������
    ������������ ��������
    ��������� ������
    ������������ ����������
    ��. �����

    (PHP 4, PHP 5, PHP 7, PHP 8)

    fopenОткрывает файл или URL

    Описание

    fopen(
        string $filename,
        string $mode,
        bool $use_include_path = false,
        ?resource $context = null
    ): resource|false

    Список параметров

    filename

    Если filename передан в форме «scheme://…»,
    он считается URL и PHP проведёт поиск обработчика протокола
    (также известного как «обёртка») для этой схемы. Если ни одна
    обёртка не закреплена за протоколом, PHP выдаст замечание,
    чтобы помочь вам отследить потенциальную проблему в вашем
    скрипте и затем продолжит выполнение, как если бы filename
    указывал на обыкновенный файл.

    Если PHP установлено, что filename указывает на
    локальный файл, тогда выполняется попытка открыть поток к этому файлу.
    Файл должен быть доступен PHP, так что вам следует убедиться,
    что права доступа на файл это разрешают.
    Если вы включили open_basedir, то накладываются
    дальнейшие ограничения.

    Если PHP установил, что filename указывает на
    зарегистрированный протокол и этот протокол зарегистрирован как
    сетевой URL, PHP выполняет проверку состояния директивы
    allow_url_fopen.
    Если она выключена, PHP выдаст предупреждение и вызов fopen закончится
    неудачей.

    Замечание:

    Список поддерживаемых протоколов доступен в разделе Поддерживаемые протоколы и обёртки.
    Некоторые протоколы (обёртки) поддерживают
    контекст и/или опции php.ini.
    Обратитесь к соответствующей странице с описанием используемого протокола
    для получения списка опций, которые могут быть установлены.
    (например, значение php.ini user_agent используется
    обёрткой http).

    На платформе Windows, необходимо экранировать все
    обратные слеши в пути к файлу или использовать прямые слеши.


    <?php
    $handle
    = fopen("c:\folder\resource.txt", "r");
    ?>

    mode

    Параметр mode указывает тип доступа, который вы
    запрашиваете у потока. Он может быть одним из следующих вариантов:


    Список возможных режимов для fopen(),
    используя mode

    mode Описание
    'r' Открывает файл только для чтения; помещает указатель
    в начало файла.
    'r+' Открывает файл для чтения и записи; помещает указатель
    в начало файла.
    'w' Открывает файл только для записи; в противном случае ведёт
    себя так же, как и 'w+'.
    'w+' Открывает файл для чтения и записи; помещает указатель
    в начало файла и обрезает файл до нулевой длины.
    Если файл не существует — пытается его создать.
    'a' Открывает файл только для записи; помещает указатель в конец
    файла. Если файл не существует — пытается его создать.
    В данном режиме функция fseek() не применима, записи всегда добавляются в конец.
    'a+' Открывает файл для чтения и записи; помещает указатель в конец
    файла. Если файл не существует — пытается его создать. В данном режиме функция fseek() влияет только на позицию чтения, записи всегда добавляются в конец.
    'x' Создаёт и открывает только для записи; помещает указатель в
    начало файла. Если файл уже существует, вызов
    fopen() закончится неудачей, вернёт false и
    выдаст ошибку уровня E_WARNING.
    Если файл не существует, попытается его создать. Это эквивалентно
    указанию флагов O_EXCL|O_CREAT для внутреннего
    системного вызова open(2).
    'x+' Создаёт и открывает для чтения и записи; в остальном имеет то же поведение, что и'x'.
    'c' Открывает файл только для записи. Если файл не существует, то он создаётся.
    Если же файл существует, то он не обрезается (в отличие от
    'w'), и вызов к этой функции не вызывает ошибку (также как
    и в случае с 'x'). Указатель на файл будет установлен
    на начало файла. Это может быть полезно при желании заблокировать
    файл (смотрите flock()) перед изменением, так как использование
    'w' может обрезать файл ещё до того как была получена блокировка
    (если вы желаете обрезать файл, можно использовать функцию
    ftruncate() после запроса на блокировку).
    'c+' Открывает файл для чтения и записи; в остальном имеет то же поведение, что и 'c'.
    'e' Установить флаг close-on-exec (закрыть при запуске) на открытый файловый
    дескриптор. Доступно только в PHP скомпилированном на системах
    поддерживающих POSIX.1-2008.

    Замечание:

    Разные семейства операционных систем имеют разные соглашения
    относительно окончания строк. Когда вы пишете текст и хотите вставить
    разрыв строки, вы должны использовать правильные символы (или символ) для
    вашей операционной системы. Системы семейства Unix используют
    n в качестве символа конца строки, системы
    семейства Windows используют rn в качестве
    символов окончания строки и системы семейства Macintosh (Mac OS Classic) используют
    r в качестве символа конца строки.

    Если вы используете неверный символ конца строки при редактировании
    файлов, вы можете обнаружить, что при открытии эти файлы «странно
    выглядят».

    Windows предлагает флаг режима текстовой трансляции
    ('t'), который автоматически переведёт
    n в rn во время работы с файлом.
    И наоборот — вы также можете использовать 'b', чтобы
    принудительно включить бинарный режим, в котором ваши данные
    не будут преобразовываться. Чтобы использовать эти режимы, укажите
    'b' или 't' последней
    буквой параметра mode.

    Флагом трансляции по умолчанию является 'b'.
    Вы можете использовать режим
    't', если работаете с текстовыми файлами и
    используете n для обозначения
    конца строки в вашем скрипте, но при этом предполагаете,
    что ваши файлы будут использоваться в таких приложениях, как «Блокнот» (в устаревших версиях).
    Во всех остальных случаях используйте флаг 'b'.

    Если вы укажете флаг ‘t’ во время работы с бинарными файлами,
    вы можете столкнуться со странными проблемами с вашими данными, включая
    повреждённые файлы изображений и проблемы с символами rn.

    Замечание:

    Опять же из соображений портируемости крайне
    рекомендуется переписать старый код, который полагается на режим
    't', чтобы вместо этого он использовал правильные
    концы строк и режим 'b'.

    Замечание:

    Параметр mode игнорируется при работе с
    обёртками потока php://output,
    php://input, php://stdin,
    php://stdout, php://stderr и
    php://fd.

    use_include_path

    Необязательный третий параметр use_include_path
    может быть установлен в ‘1’ или true, если вы также хотите провести
    поиск файла в include_path.

    context

    Ресурс (resource) с контекстом потока.

    Возвращаемые значения

    Возвращает указатель на файл в случае успешного выполнения или false в случае возникновения ошибки

    Ошибки

    В случае неудачного завершения работы генерируется ошибка уровня E_WARNING.

    Список изменений

    Версия Описание
    7.0.16, 7.1.2 Добавлена опция 'e'.

    Примеры

    Пример #1 Примеры использования fopen()


    <?php
    $handle
    = fopen("/home/rasmus/file.txt", "r");
    $handle = fopen("/home/rasmus/file.gif", "wb");
    $handle = fopen("http://www.example.com/", "r");
    $handle = fopen("ftp://user:password@example.com/somefile.txt", "w");
    ?>

    Примечания

    Внимание

    При использовании SSL, Microsoft IIS нарушает протокол, закрывая соединение без отправки индикатора close_notify. PHP сообщит об этом как «SSL: Fatal Protocol Error» в тот момент, когда вы достигнете конца данных. Чтобы обойти это, вы должны установить error_reporting на уровень, исключающий E_WARNING. PHP умеет определять, что на стороне сервера находится проблемный IIS при открытии потока с помощью обёртки https:// и не выводит предупреждение. Если вы используете fsockopen() для создания ssl:// сокета, вы сами отвечаете за определение и подавление этого предупреждения.

    Замечание:

    Если вы сталкиваетесь с проблемами во время чтения или записи
    файлов, и вы используете PHP в виде серверного модуля, убедитесь
    в том, что процесс сервера имеет доступ к используемым вами файлам и директориям.

    Замечание:

    Данная функция также может принимать директории в качестве параметра filename.
    Если вы не знаете, является ли filename файлом или директорией,
    то вам может понадобиться использовать функцию is_dir()
    до вызова функции fopen().

    Смотрите также

    • Поддерживаемые протоколы и обёртки
    • fclose() — Закрывает открытый дескриптор файла
    • fgets() — Читает строку из файла
    • fread() — Бинарно-безопасное чтение файла
    • fwrite() — Бинарно-безопасная запись в файл
    • fsockopen() — Открывает соединение с интернет-сокетом или доменным сокетом Unix
    • file() — Читает содержимое файла и помещает его в массив
    • file_exists() — Проверяет существование указанного файла или каталога
    • is_readable() — Определяет существование файла и доступен ли он для чтения
    • stream_set_timeout() — Установить значение времени ожидания для потока
    • popen() — Открывает файловый указатель процесса
    • stream_context_create() — Создаёт контекст потока
    • umask() — Изменяет текущую umask
    • SplFileObject

    chapman at worldtakeoverindustries dot com

    11 years ago


    Note - using fopen in 'w' mode will NOT update the modification time (filemtime) of a file like you may expect. You may want to issue a touch() after writing and closing the file which update its modification time. This may become critical in a caching situation, if you intend to keep your hair.

    Anon.

    2 years ago


    /***** GENTLE REMINDER *****/
    Really important. Do NOT use the "w" flag unless you want to delete everything in the file.

    php at delhelsa dot com

    14 years ago


    With php 5.2.5 on Apache 2.2.4, accessing files on an ftp server with fopen() or readfile() requires an extra forwardslash if an absolute path is needed.

    i.e., if a file called bullbes.txt is stored under /var/school/ on ftp server example.com and you're trying to access it with user blossom and password buttercup, the url would be:

    ftp://blossom:buttercup@example.com//var/school/bubbles.txt

    Note the two forwardslashes. It looks like the second one is needed so the server won't interpret the path as relative to blossom's home on townsville.


    petepostma-deletethis at gmail dot com

    6 years ago


    The verbal descriptions take a while to read through to get a feel for the expected results for fopen modes. This csv table can help break it down for quicker understanding to find which mode you are looking for:

    Mode,Creates,Reads,Writes,Pointer Starts,Truncates File,Notes,Purpose
    r,,y,,beginning,,fails if file doesn't exist,basic read existing file
    r+,,y,y,beginning,,fails if file doesn't exist,basic r/w existing file
    w,y,,y,beginning+end,y,,"create, erase, write file"
    w+,y,y,y,beginning+end,y,,"create, erase, write file with read option"
    a,y,,y,end,,,"write from end of file, create if needed"
    a+,y,y,y,end,,,"write from end of file, create if needed, with read options"
    x,y,,y,beginning,,fails if file exists,"like w, but prevents over-writing an existing file"
    x+,y,y,y,beginning,,fails if file exists,"like w+, but prevents over writing an existing file"
    c,y,,y,beginning,,,open/create a file for writing without deleting current content
    c+,y,y,y,beginning,,,"open/create a file that is read, and then written back down"


    php-manual at merlindynamics dot com

    3 years ago


    There is an undocumented mode for making fopen non-blocking (not working on windows). By adding 'n' to the mode parameter, fopen will not block, however if the pipe does not exist an error will be raised.

    $fp = fopen("/tmp/debug", "a"); //blocks if pipe does not exist

    $fp = fopen("/tmp/debug", "an"); //raises error on pipe not exist


    durwood at speakeasy dot NOSPAM dot net

    17 years ago


    I couldn't for the life of me get a certain php script working when i moved my server to a new Fedora 4 installation. The problem was that fopen() was failing when trying to access a file as a URL through apache -- even though it worked fine when run from the shell and even though the file was readily readable from any browser.  After trying to place blame on Apache, RedHat, and even my cat and dog, I finally ran across this bug report on Redhat's website:

    https://bugzilla.redhat.com/bugzilla/show_bug.cgi?id=164700

    Basically the problem was SELinux (which I knew nothing about) -- you have to run the following command in order for SELinux to allow php to open a web file:

    /usr/sbin/setsebool httpd_can_network_connect=1

    To make the change permanent, run it with the -P option:

    /usr/sbin/setsebool -P httpd_can_network_connect=1

    Hope this helps others out -- it sure took me a long time to track down the problem.


    ideacode

    17 years ago


    Note that whether you may open directories is operating system dependent. The following lines:

    <?php
    // Windows ($fh === false)
    $fh = fopen('c:\Temp', 'r');// UNIX (is_resource($fh) === true)
    $fh = fopen('/tmp', 'r');
    ?>

    demonstrate that on Windows (2000, probably XP) you may not open a directory (the error is "Permission Denied"), regardless of the security permissions on that directory.

    On UNIX, you may happily read the directory format for the native filesystem.


    dan at cleandns dot com

    19 years ago


    <?php
    #going to update last users counter script since
    #aborting a write because a file is locked is not correct.
    $counter_file = '/tmp/counter.txt';
    clearstatcache();
    ignore_user_abort(true);     ## prevent refresh from aborting file operations and hosing file
    if (file_exists($counter_file)) {
      
    $fh = fopen($counter_file, 'r+');
        while(
    1) {
          if (
    flock($fh, LOCK_EX)) {
            
    #$buffer = chop(fgets($fh, 2));
            
    $buffer = chop(fread($fh, filesize($counter_file)));
            
    $buffer++;
            
    rewind($fh);
            
    fwrite($fh, $buffer);
            
    fflush($fh);
            
    ftruncate($fh, ftell($fh));    
            
    flock($fh, LOCK_UN);
             break;
          }
       }
    }
    else {
      
    $fh = fopen($counter_file, 'w+');
      
    fwrite($fh, "1");
      
    $buffer="1";
    }
    fclose($fh);

    print

    "Count is $buffer";?>

    php at richardneill dot org

    11 years ago


    fopen() will block if the file to be opened is a fifo. This is true whether it's opened in "r" or "w" mode.  (See man 7 fifo: this is the correct, default behaviour; although Linux supports non-blocking fopen() of a fifo, PHP doesn't).
    The consequence of this is that you can't discover whether an initial fifo read/write would block because to do that you need stream_select(), which in turn requires that fopen() has happened!

    etters dot ayoub at gmail dot com

    5 years ago


    This functions check recursive permissions and recursive existence parent folders, before creating a folder. To avoid the generation of errors/warnings.

    /**
    * This functions check recursive permissions and recursive existence parent folders,
    * before creating a folder. To avoid the generation of errors/warnings.
    *
    * @return bool
    *     true folder has been created or exist and writable.
    *     False folder not exist and cannot be created.
    */
    function createWritableFolder($folder)
    {
        if (file_exists($folder)) {
            // Folder exist.
            return is_writable($folder);
        }
        // Folder not exit, check parent folder.
        $folderParent = dirname($folder);
        if($folderParent != '.' && $folderParent != '/' ) {
            if(!createWritableFolder(dirname($folder))) {
                // Failed to create folder parent.
                return false;
            }
            // Folder parent created.
        }

        if ( is_writable($folderParent) ) {
            // Folder parent is writable.
            if ( mkdir($folder, 0777, true) ) {
                // Folder created.
                return true;
            }
            // Failed to create folder.
        }
        // Folder parent is not writable.
        return false;
    }

    /**
    * This functions check recursive permissions and recursive existence parent folders,
    * before creating a file/folder. To avoid the generation of errors/warnings.
    *
    * @return bool
    *     true has been created or file exist and writable.
    *     False file not exist and cannot be created.
    */
    function createWritableFile($file)
    {
        // Check if conf file exist.
        if (file_exists($file)) {
            // check if conf file is writable.
            return is_writable($file);
        }

        // Check if conf folder exist and try to create conf file.
        if(createWritableFolder(dirname($file)) && ($handle = fopen($file, 'a'))) {
            fclose($handle);
            return true; // File conf created.
        }
        // Inaccessible conf file.
        return false;
    }


    splogamurugan at gmail dot com

    11 years ago


    While opening a file with multibyte data (Ex: données multi-octets), faced some issues with the encoding. Got to know that it uses  windows-1250. Used iconv to convert it to UTF-8 and it resolved the issue. 

    <?php

    function utf8_fopen_read($fileName) {

       
    $fc = iconv('windows-1250', 'utf-8', file_get_contents($fileName));

       
    $handle=fopen("php://memory", "rw");

       
    fwrite($handle, $fc);

       
    fseek($handle, 0);

        return
    $handle;

    }

    ?>



    Example usage:

    <?php

    $fh
    = utf8_fopen_read("./tpKpiBundle.csv");

    while ((
    $data = fgetcsv($fh, 1000, ",")) !== false) {

        foreach (
    $data as $value) {

            echo
    $value . "<br />n";

        }

    }

    ?>



    Hope it helps.


    info at b1g dot de

    17 years ago


    Simple class to fetch a HTTP URL. Supports "Location:"-redirections. Useful for servers with allow_url_fopen=false. Works with SSL-secured hosts.

    <?php

    #usage:

    $r = new HTTPRequest('http://www.example.com');

    echo
    $r->DownloadToString();

    class

    HTTPRequest

    {

        var
    $_fp;        // HTTP socket

       
    var $_url;        // full URL

       
    var $_host;        // HTTP host

       
    var $_protocol;    // protocol (HTTP/HTTPS)

       
    var $_uri;        // request URI

       
    var $_port;        // port

       
        // scan url

    function _scan_url()

        {

           
    $req = $this->_url;
    $pos = strpos($req, '://');

           
    $this->_protocol = strtolower(substr($req, 0, $pos));
    $req = substr($req, $pos+3);

           
    $pos = strpos($req, '/');

            if(
    $pos === false)

               
    $pos = strlen($req);

           
    $host = substr($req, 0, $pos);

           
            if(

    strpos($host, ':') !== false)

            {

                list(
    $this->_host, $this->_port) = explode(':', $host);

            }

            else

            {

               
    $this->_host = $host;

               
    $this->_port = ($this->_protocol == 'https') ? 443 : 80;

            }
    $this->_uri = substr($req, $pos);

            if(
    $this->_uri == '')

               
    $this->_uri = '/';

        }
    // constructor

       
    function HTTPRequest($url)

        {

           
    $this->_url = $url;

           
    $this->_scan_url();

        }
    // download URL to string

       
    function DownloadToString()

        {

           
    $crlf = "rn";
    // generate request

           
    $req = 'GET ' . $this->_uri . ' HTTP/1.0' . $crlf

               
    .    'Host: ' . $this->_host . $crlf

               
    .    $crlf;
    // fetch

           
    $this->_fp = fsockopen(($this->_protocol == 'https' ? 'ssl://' : '') . $this->_host, $this->_port);

           
    fwrite($this->_fp, $req);

            while(
    is_resource($this->_fp) && $this->_fp && !feof($this->_fp))

               
    $response .= fread($this->_fp, 1024);

           
    fclose($this->_fp);
    // split header and body

           
    $pos = strpos($response, $crlf . $crlf);

            if(
    $pos === false)

                return(
    $response);

           
    $header = substr($response, 0, $pos);

           
    $body = substr($response, $pos + 2 * strlen($crlf));
    // parse headers

           
    $headers = array();

           
    $lines = explode($crlf, $header);

            foreach(
    $lines as $line)

                if((
    $pos = strpos($line, ':')) !== false)

                   
    $headers[strtolower(trim(substr($line, 0, $pos)))] = trim(substr($line, $pos+1));
    // redirection?

           
    if(isset($headers['location']))

            {

               
    $http = new HTTPRequest($headers['location']);

                return(
    $http->DownloadToString($http));

            }

            else

            {

                return(
    $body);

            }

        }

    }

    ?>


    apathetic012 at gmail dot com

    10 years ago


    a variable $http_response_header is available when doing the fopen(). Which contains an array of the response header.

    Derrick

    4 months ago


    Opening a file in "r+" mode, and then trying to set the file pointer position with ftruncate before reading the file will result in file data loss, as though you opened the file in "w" mode.

    EX:

    $File = fopen($FilePath,"r+");  // OPEN FILE IN READ-WRITE

    ftruncate($File, 0);  // SET POINTER POSITION (Will Erase Data)

    while(! feof($File)) {  // CONTINUE UNTIL END OF FILE IS REACHED

        $Line = fgets($File);  // GET A LINE FROM THE FILE INTO STRING
        $Line = trim($Line);  // TRIM STRING OF NEW LINE
    }

    ftruncate($File,0); // (Will Not Erase Data)

    fclose($File);


    wvss at gmail dot com

    1 year ago


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
    <?php
    // generiereHostliste.phpfunction generiereHostliste($file) {// aus Rechnerliste.csv lesen
      
    $fp = fopen($file, "r");
       while(
    $row = fgetcsv($fp, 0, ";")) {      
           
    $liste[]=[$row[0].";10.16.".$row[1].".".$row[2]];

               } 

    fclose($fp);// in Hostliste.csv schreiben
      
    $fp = fopen("Hostliste.csv", "w");
       foreach(
    $liste as $row) {
           echo
    "<pre>";
          
    print_r($row);
           echo
    "</pre>";
           
    fputcsv($fp, $row, ";");
       }
      
    fclose($fp);
    }
    // Test
    $file = "Rechnerliste.csv";
    generiereHostliste($file);?>
    </body>
    </html>

    ken dot gregg at rwre dot com

    19 years ago


    PHP will open a directory if a path with no file name is supplied. This just bit me. I was not checking the filename part of a concatenated string.

    For example:

    <?php

    $fd
    = fopen('/home/mydir/' . $somefile, 'r');

    ?>



    Will open the directory if $somefile = ''

    If you attempt to read using the file handle you will get the binary directory contents. I tried append mode and it errors out so does not seem to be dangerous.

    This is with FreeBSD 4.5 and PHP 4.3.1. Behaves the same on 4.1.1 and PHP 4.1.2. I have not tested other version/os combinations.


    flobee

    17 years ago


    download: i need a function to simulate a "wget url" and do not buffer the data in the memory to avoid thouse problems on large files:
    <?php
    function download($file_source, $file_target) {
           
    $rh = fopen($file_source, 'rb');
           
    $wh = fopen($file_target, 'wb');
            if (
    $rh===false || $wh===false) {
    // error reading or opening file
              
    return true;
            }
            while (!
    feof($rh)) {
                if (
    fwrite($wh, fread($rh, 1024)) === FALSE) {
                      
    // 'Download error: Cannot write to file ('.$file_target.')';
                      
    return true;
                   }
            }
           
    fclose($rh);
           
    fclose($wh);
           
    // No error
           
    return false;
        }
    ?>

    kasper at webmasteren dot eu

    11 years ago


    "Do not use the following reserved device names for the name of a file:
    CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1,
    LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. Also avoid these names
    followed immediately by an extension; for example, NUL.txt is not recommended.
    For more information, see Namespaces"
    it is a windows limitation.
    see:
    http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx

    keithm at aoeex dot NOSPAM dot com

    21 years ago


    I was working on a consol script for win32 and noticed a few things about it.  On win32 it appears that you can't re-open the input stream for reading, but rather you have to open it once, and read from there on.  Also, i don't know if this is a bug or what but it appears that fgets() reads until the new line anyway.  The number of characters returned is ok, but it will not halt reading and return to the script.  I don't know of a work around for this right now, but i'll keep working on it.

    This is some code to work around the close and re-open of stdin.

    <?php

    function read($length='255'){

        if (!isset(
    $GLOBALS['StdinPointer'])){

           
    $GLOBALS['StdinPointer']=fopen("php://stdin","r");

        }

       
    $line=fgets($GLOBALS['StdinPointer'],$length);

        return
    trim($line);

    }

    echo
    "Enter your name: ";

    $name=read();

    echo
    "Enter your age: ";

    $age=read();

    echo
    "Hi $name, Isn't it Great to be $age years old?";

    @
    fclose($StdinPointer);

    ?>


    ceo at l-i-e dot com

    17 years ago


    If you need fopen() on a URL to timeout, you can do like:
    <?php
      $timeout
    = 3;
     
    $old = ini_set('default_socket_timeout', $timeout);
     
    $file = fopen('http://example.com', 'r');
     
    ini_set('default_socket_timeout', $old);
     
    stream_set_timeout($file, $timeout);
     
    stream_set_blocking($file, 0);
     
    //the rest is standard
    ?>

    wvss at gmail dot com

    1 year ago


    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
    <?php
    // generiereHostliste.phpfunction generiereHostliste($file) {// aus Rechnerliste.csv lesen
      
    $fp = fopen($file, "r");
       while(
    $row = fgetcsv($fp, 0, ";")) {      
           
    $liste[]=[$row[0].";10.16.".$row[1].".".$row[2]];

               } 

    fclose($fp);// in Hostliste.csv schreiben
      
    $fp = fopen("Hostliste.csv", "w");
       foreach(
    $liste as $row) {
           echo
    "<pre>";
          
    print_r($row);
           echo
    "</pre>";
           
    fputcsv($fp, $row, ";");
       }
      
    fclose($fp);
    }
    // Test
    $file = "Rechnerliste.csv";
    generiereHostliste($file);?>
    </body>
    </html>

    k-gun at git dot io

    3 years ago


    Seems not documented here but keep in mind, when $filename contains null byte () then a TypeError will be thrown with message such;

    TypeError: fopen() expects parameter 1 to be a valid path, string given in ...


    sean downey

    15 years ago


    when using ssl / https on windows i would get the error:

    "Warning: fopen(https://example.com): failed to open stream: Invalid argument in someSpecialFile.php on line 4344534"

    This was because I did not have the extension "php_openssl.dll" enabled.

    So if you have the same problem, goto your php.ini file and enable it :)


    I have the following code where I am trying to open a text file.

    char frd[32]="word-list.txt";
       FILE *rd=fopen(frd,"rb");
       if(!rd)
           std::cout<<"Coudn't open filet"<<frd;
    

    I am using vc 2010 and the file is in the debug directory of this project.
    Can anyone tell me why it is not able to open the file?

    Alan Birtles's user avatar

    Alan Birtles

    31.6k4 gold badges31 silver badges59 bronze badges

    asked Dec 26, 2011 at 7:48

    John's user avatar

    4

    #include<stdio.h>
    #include <errno.h>
    
    int main()
    {
    errno = 0;
    FILE *fb = fopen("/home/jeegar/filename","r");
    if(fb==NULL)
        printf("its null");
    else
        printf("working");
    
    
    printf("Error %d n", errno);
    
    
    }
    

    this way if fopen gets fail then it will set error number you can find those error number list at here http://pubs.opengroup.org/onlinepubs/009695399/functions/fopen.html

    answered Dec 26, 2011 at 8:04

    Jeegar Patel's user avatar

    Jeegar PatelJeegar Patel

    26.1k51 gold badges149 silver badges218 bronze badges

    3

    Look at the errno variable which is set in the event of an error. It’s a global variable. It’s been a while, but probably include errno.h which will give you the definition.

    answered Dec 26, 2011 at 7:57

    Francis Upton IV's user avatar

    Francis Upton IVFrancis Upton IV

    19.3k3 gold badges53 silver badges57 bronze badges

    You can do man fopen — it says Upon successful completion fopen() return a FILE pointer. Otherwise, NULL is returned and errno is set to indicate the error.

    Please check whether the file exists in the execution path or in your program, check the errno

    answered Dec 26, 2011 at 8:00

    Sangeeth Saravanaraj's user avatar

    r Open for reading (existing file only) and
    rb Open for reading (existing file only) in binary mode
    . Make sure you have the file in your working directory.

    answered Dec 26, 2011 at 7:56

    dicaprio's user avatar

    dicapriodicaprio

    7132 gold badges8 silver badges25 bronze badges

    1

    ОБЗОР

    #include <stdio.h>


    FILE *fopen(const char *path, const char *mode);
    FILE *fdopen(int fd, const char *mode);
    FILE *freopen(const char *path, const char *mode, FILE *stream);

    Требования макроса тестирования свойств для glibc
    (см. feature_test_macros(7)):

    fdopen(): _POSIX_C_SOURCE >= 1 || _XOPEN_SOURCE || _POSIX_SOURCE

    ОПИСАНИЕ

    Функция fopen() открывает файл с именем, которое задано в виде строки в
    path, и связывает его с потоком.

    Параметр mode указывает на строку, начинающуюся с одной из следующих
    последовательностей (за ними могут следовать дополнительные символы,
    описанные далее):

    r
    Открыть текстовый файл для чтения. Поток совмещается с началом файла.
    r+
    Открыть для чтения и записи. Поток совмещается с началом файла.
    w
    Обрезать файл до нулевой длины или создать текстовый файл для записи. Поток
    совмещается с началом файла.
    w+
    Открыть для чтения и записи. Файл создаётся, если его не существует, в
    противном случае он обрезается. Поток совмещается с началом файла.
    a
    Открыть для добавления (записи в конец файла). Файл создаётся, если его не
    существует. Поток совмещается с концом файла.
    a+
    Открыть для чтения и добавления (записи в конец файла). Файл создаётся, если
    не существует. Начальное положение в файле для чтения устанавливается в
    начало файла, но вывод всегда добавляется в конец файла.

    Строка mode может также содержать символ «b» в качестве последнего
    символа или символа между двумя символами в любых описанных выше
    двухсимвольных комбинациях. Это требуется только для совместимости с C89 и
    не оказывает никакого влияния; символ «b» игнорируется во всех
    POSIX-совместимых системах, включая Linux. Другие системы могут по-разному
    обращаться с текстовыми и двоичными файлами, и добавление «b» может
    оказаться полезным, если вы осуществляете ввод-вывод в двоичный файл и
    ожидаете, что ваша программа может быть перенесена в не UNIX окружение.

    О имеющихся расширениях mode в glibc смотрите ЗАМЕЧАНИЯ далее.

    Любой созданный файл будет иметь атрибуты S_IRUSR | S_IWUSR |
    S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH (0666), как изменённые в
    соответствии со значением umask процесса (смотрите umask(2)).

    Чтение и запись могут перемешиваться друг с другом в потоке, открытом для
    чтения/записи, в любом порядке). Заметим, что в ANSI C требуется, чтобы
    между выводом и вводом использовались функции позиционирования в файле, если
    операция ввода не встретила конец файла. Если это условие не выполняется, то
    при чтении разрешается возвращать результат, не совпадающий с данными самой
    последней записи. Поэтому рекомендуется (а иногда и действительно необходимо
    в Linux) использовать функции fseek(3) или fgetpos(3) между операциями
    чтения и записи в одном потоке. Эти операции могут фактически быть пустыми
    (например, fseek(…, 0L, SEEK_CUR), вызванная для того, чтобы возник её
    побочный эффект синхронизации).

    Открытие файла в режиме дописывания (a в качестве первого символа
    mode) приводит к тому, что все последующие операции записи в этот поток
    производятся в конец файла, как если бы перед ними была вызвана:

        fseek(stream, 0, SEEK_END);
    

    Функция fdopen() связывает поток с существующим дескриптором файла
    fd. Режим mode потока (одно из следующих значений: «r», «r+», «w»,
    ,w+», «a», «a+») должен быть совместим с режимом дескриптора
    файла. Указатель положения в файле в новом потоке принимает значение, равное
    значению у fd, а указатели ошибок и конца файла очищаются. Режимы «w» или
    «w+» не обрезают файл. При этом не делается копия дескриптора файла и он
    будет закрыт одновременно с закрытием потока, созданного
    fdopen(). Результат применения fdopen() к общему объекту памяти не
    определён.

    Функция freopen() открывает файл с именем path и связывает его с
    потоком stream. Исходный поток (если такой существовал)
    закрывается. Значение параметра mode такое же как у функции
    fopen(). Основной задачей функции freopen() является смена файла,
    связанного со стандартным текстовым потоком (stderr, stdin или
    stdout).

    ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ

    При успешном выполнении fopen(), fdopen() и freopen() возвращается
    указатель FILE. В противном случае возвращается NULL и errno
    присваивается код ошибки.

    ОШИБКИ

    EINVAL
    Передано неверное значение mode в fopen(), fdopen() или
    freopen().

    Функции fopen(), fdopen() и freopen() могут также завершаться с
    ошибками и устанавливают значение errno равным какому-либо значению из
    определённых в malloc(3).

    Функция fopen() при ошибках устанавливает значение errno равным
    какому-либо значению из определённых в open(2).

    Функция fdopen() при ошибках устанавливает значение errno равным
    какому-либо значению из определённых в fcntl(2).

    Функция freopen() при ошибках устанавливает errno равным какому-либо
    значению из определённых в open(2), fclose(3) и fflush(3).

    АТРИБУТЫ

    Описание терминов данного раздела смотрите в attributes(7).

    Интерфейс Атрибут Значение
    fopen(),
    fdopen(),
    freopen()
    безвредность в нитях безвредно (MT-Safe)

    СООТВЕТСТВИЕ СТАНДАРТАМ

    fopen(), freopen(): POSIX.1-2001, POSIX.1-2008, C89, C99.

    fdopen(): POSIX.1-2001, POSIX.1-2008.

    Замечания по glibc

    Библиотека GNU C предоставляет следующие расширения строки в mode:

    c (начиная с glibc 2.3.3)
    Не выполнять операцию открытия, последующие чтение и запись, точки отмены
    нити (thread cancellation points). Этот флаг игнорируется для fdopen().
    e (начиная с glibc 2.7)
    Открыть файл с флагом O_CLOEXEC. Подробности смотрите в open(2). Этот
    флаг игнорируется для fdopen().
    m (начиная с glibc 2.3)
    Пытаться получить доступ к файлу с помощью mmap(2), а не с помощью
    системных операций ввода-вывода (read(2), write(2)). В настоящее время
    mmap(2) используется только для файла, открытого на чтение.
    x
    Открыть файл в монопольном режиме (как с флагом O_EXCL у
    open(2)). Если файл уже существует, то fopen() завершается с ошибкой и
    устанавливает значение errno равное EEXIST. Этот флаг игнорируется для
    fdopen().

    В дополнении к этим символам, для fopen() и freopen() поддерживается
    следующий синтаксис в mode:

    ,ccs=строка

    Передаваемая строка используется как имя набора символов и поток
    помечается как широкосимвольный. С того момента внутренние функции
    преобразования перекодируют данные ввода-вывода в соответствии с набором
    символов с именем строка. Если синтаксис ,ccs=строка не указан, то
    широкосимвольность потока определяется по первой файловой операции. Если это
    операция является широкосимвольной, то поток помечается как широкосимвольный
    и загружаются функции для перекодировки.

    description title ms.date api_name api_location api_type topic_type f1_keywords helpviewer_keywords

    Learn more about: fopen, _wfopen

    fopen, _wfopen

    04/27/2023

    _wfopen

    fopen

    _o__wfopen

    _o_fopen

    msvcrt.dll

    msvcr80.dll

    msvcr90.dll

    msvcr100.dll

    msvcr100_clr0400.dll

    msvcr110.dll

    msvcr110_clr0400.dll

    msvcr120.dll

    msvcr120_clr0400.dll

    ucrtbase.dll

    api-ms-win-crt-stdio-l1-1-0.dll

    DLLExport

    apiref

    STDIO/fopen

    CORECRT_WSTDIO/_wfopen

    TCHAR/_tfopen

    fopen

    _wfopen

    _tfopen

    opening files, for file I/O

    wfopen function

    tfopen function

    _tfopen function

    _wfopen function

    files [C++], opening

    fopen function

    fopen, _wfopen

    Opens a file. More-secure versions of these functions that perform more parameter validation and return error codes are available; see fopen_s, _wfopen_s.

    Syntax

    FILE *fopen(
       const char *filename,
       const char *mode
    );
    FILE *_wfopen(
       const wchar_t *filename,
       const wchar_t *mode
    );

    Parameters

    filename
    File name.

    mode
    Kind of access that’s enabled.

    Return value

    Each of these functions returns a pointer to the open file. A null pointer value indicates an error. If filename or mode is NULL or an empty string, these functions trigger the invalid parameter handler, which is described in Parameter validation. If execution is allowed to continue, these functions return NULL and set errno to EINVAL.

    For more information, see errno, _doserrno, _sys_errlist, and _sys_nerr.

    Remarks

    The fopen function opens the file specified by filename. By default, a narrow filename string is interpreted using the ANSI codepage (CP_ACP). In Windows Desktop applications, it can be changed to the OEM codepage (CP_OEMCP) by using the SetFileApisToOEM function. You can use the AreFileApisANSI function to determine whether filename is interpreted using the ANSI or the system default OEM codepage. _wfopen is a wide-character version of fopen; the _wfopen arguments are wide-character strings. Otherwise, _wfopen and fopen behave identically. Just using _wfopen doesn’t affect the coded character set that’s used in the file stream.

    fopen accepts paths that are valid on the file system at the point of execution; fopen accepts UNC paths and paths that involve mapped network drives as long as the system that executes the code has access to the share or mapped drive at the time of execution. When you construct paths for fopen, make sure that drives, paths, or network shares are available in the execution environment. You can use either forward slashes (/) or backslashes () as the directory separators in a path.

    Always check the return value to see whether the pointer is NULL before you perform any other operations on the file. If an error occurs, the global variable errno is set, and may be used to obtain specific error information. For more information, see errno, _doserrno, _sys_errlist, and _sys_nerr.

    By default, this function’s global state is scoped to the application. To change it, see Global state in the CRT.

    Unicode support

    fopen supports Unicode file streams. To open a Unicode file, pass a ccs=encoding flag that specifies the desired encoding to fopen, as follows.

    FILE *fp = fopen("newfile.txt", "rt+, ccs=UTF-8");

    Allowed values for ccs encoding are UNICODE, UTF-8, and UTF-16LE.

    When a file is opened in Unicode mode, input functions translate the data that’s read from the file into UTF-16 data stored as type wchar_t. Functions that write to a file opened in Unicode mode expect buffers that contain UTF-16 data stored as type wchar_t. If the file is encoded as UTF-8, then UTF-16 data is translated into UTF-8 when it’s written. The file’s UTF-8-encoded content is translated into UTF-16 when it’s read. An attempt to read or write an odd number of bytes in Unicode mode causes a parameter validation error. To read or write data that’s stored in your program as UTF-8, use a text or binary file mode instead of a Unicode mode. You’re responsible for any required encoding translation.

    If the file already exists and is opened for reading or appending, then any byte order mark (BOM) in the file determines the encoding. The BOM encoding takes precedence over the encoding specified by the ccs flag. The ccs encoding is only used when no BOM is present or the file is a new file.

    [!NOTE]
    BOM detection only applies to files that are opened in Unicode mode (that is, by passing the ccs flag).

    The following table summarizes the modes that are used for various ccs flags given to fopen and Byte Order Marks in the file.

    Encodings used based on ccs flag and BOM

    ccs flag No BOM (or new file) BOM: UTF-8 BOM: UTF-16
    UNICODE UTF-16LE UTF-8 UTF-16LE
    UTF-8 UTF-8 UTF-8 UTF-16LE
    UTF-16LE UTF-16LE UTF-8 UTF-16LE

    Files opened for writing in Unicode mode have a BOM written to them automatically.

    If mode is a, ccs=encoding for some encoding value, fopen first tries to open the file by using both read and write access. If this action succeeds, the function reads the BOM to determine the encoding for the file. If it fails, the function uses the default encoding for the file. In either case, fopen reopens the file using write-only access. (This behavior applies to "a" mode only, not to "a+" mode.)

    Generic-text routine mappings

    TCHAR.H routine _UNICODE and _MBCS not defined _MBCS defined _UNICODE defined
    _tfopen fopen fopen _wfopen

    The character string mode specifies the kind of access that is requested for the file, as follows.

    mode Access
    "r" Opens for reading. If the file doesn’t exist or can’t be found, the fopen call fails.
    "w" Opens an empty file for writing. If the given file exists, its contents are destroyed.
    "a" Opens for writing at the end of the file (appending) without removing the end-of-file (EOF) marker before new data is written to the file. Creates the file if it doesn’t exist.
    "r+" Opens for both reading and writing. The file must exist.
    "w+" Opens an empty file for both reading and writing. If the file exists, its contents are destroyed.
    "a+" Opens for reading and appending. The appending operation includes the removal of the EOF marker before new data is written to the file. The EOF marker isn’t restored after writing is completed. Creates the file if it doesn’t exist.

    When a file is opened by using the "a" access type or the "a+" access type, all write operations occur at the end of the file. The file pointer can be repositioned by using fseek or rewind, but is always moved back to the end of the file before any write operation is performed. Therefore, existing data can’t be overwritten.

    The "a" mode doesn’t remove the EOF marker before it appends to the file. After appending has occurred, the MS-DOS TYPE command only shows data up to the original EOF marker and not any data appended to the file. Before it appends to the file, the "a+" mode does remove the EOF marker. After appending, the MS-DOS TYPE command shows all data in the file. The "a+" mode is required for appending to a stream file that is terminated with the CTRL+Z EOF marker.

    When the "r+", "w+", or "a+" access type is specified, both reading and writing are enabled (the file is said to be open for «update»). However, when you switch from reading to writing, the input operation must encounter an EOF marker. If there’s no EOF, you must use an intervening call to a file positioning function. The file positioning functions are fsetpos, fseek, and rewind. When you switch from writing to reading, you must use an intervening call to either fflush or to a file positioning function.

    In addition to the earlier values, the following characters can be appended to mode to specify the translation mode for newline characters.

    mode modifier Translation mode
    t Open in text (translated) mode. Carriage return-line feed (CR-LF) combinations are translated into single line feeds (LF) on input and LF characters are translated to CR-LF combinations on output. Also, CTRL+Z is interpreted as an end-of-file character on input.
    b Open in binary (untranslated) mode; translations involving carriage-return and line feed characters are suppressed.

    In text mode, CTRL+Z is interpreted as an EOF character on input. In files that are opened for reading/writing by using "a+", fopen checks for a CTRL+Z at the end of the file and removes it, if it’s possible. It’s removed because using fseek and ftell to move within a file that ends with CTRL+Z may cause fseek to behave incorrectly near the end of the file.

    In text mode, carriage return-line feed (CRLF) combinations are translated into single line feed (LF) characters on input, and LF characters are translated to CRLF combinations on output. When a Unicode stream-I/O function operates in text mode (the default), the source or destination stream is assumed to be a sequence of multibyte characters. Therefore, the Unicode stream-input functions convert multibyte characters to wide characters (as if by a call to the mbtowc function). For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters (as if by a call to the wctomb function).

    If t or b isn’t given in mode, the default translation mode is defined by the global variable _fmode. If t or b is prefixed to the argument, the function fails and returns NULL.

    For more information about how to use text and binary modes in Unicode and multibyte stream-I/O, see Text and binary mode file I/O and Unicode stream I/O in text and binary modes.

    The following options can be appended to mode to specify more behaviors.

    mode modifier Behavior
    x Forces the function to fail if filename already exists. Can only be used with the «w» or «w+» specifiers.
    c Enable the commit flag for the associated filename so that the contents of the file buffer are written directly to disk if either fflush or _flushall is called.
    n Reset the commit flag for the associated filename to «no-commit.» This flag is the default. It also overrides the global commit flag if you link your program with COMMODE.OBJ. The global commit flag default is «no-commit» unless you explicitly link your program with COMMODE.OBJ (see Link options).
    N Specifies that the file isn’t inherited by child processes.
    S Specifies that caching is optimized for, but not restricted to, sequential access from disk.
    R Specifies that caching is optimized for, but not restricted to, random access from disk.
    T Specifies a file that isn’t written to disk unless memory pressure requires it.
    D Specifies a temporary file that’s deleted when the last file pointer to it is closed.
    ccs=encoding Specifies the encoded character set to use (one of UTF-8, UTF-16LE, or UNICODE) for this file. Leave unspecified if you want ANSI encoding. This flag is separated from flags that precede it by a comma (,). For example: FILE *f = fopen("newfile.txt", "rt+, ccs=UTF-8");

    Valid characters for the mode string that is used in fopen and _fdopen correspond to oflag arguments that are used in _open and _sopen, as follows.

    Characters in mode string Equivalent oflag value for _open/_sopen
    a `_O_WRONLY
    a+ `_O_RDWR
    r _O_RDONLY
    r+ _O_RDWR
    w _O_WRONLY (usually `_O_WRONLY
    w+ _O_RDWR (usually `_O_RDWR
    b _O_BINARY
    t _O_TEXT (translated)
    x _O_EXCL
    c None
    n None
    S _O_SEQUENTIAL
    R _O_RANDOM
    T _O_SHORTLIVED
    D _O_TEMPORARY
    ccs=UNICODE _O_WTEXT
    *ccs=UTF-8* _O_UTF8
    ccs=UTF-16LE _O_UTF16

    If you’re using rb mode, you don’t have to port your code, and if you expect to read most of a large file or aren’t concerned about network performance, you might also consider whether to use memory mapped Win32 files as an option.

    Regarding T and D:

    • T avoids writing the file to disk as long as memory pressure doesn’t require it. For more information, see FILE_ATTRIBUTE_TEMPORARY in File attribute constants, and also this blog post It’s only temporary.
    • D specifies a regular file that is written to disk. The difference is that it’s automatically deleted when it’s closed.
      You can combine TD to get both semantics.

    The c, n, R, S, t, T, and D mode options are Microsoft extensions for fopen and _wfopen and shouldn’t be used when you want ANSI portability.

    Requirements

    Function Required header
    fopen <stdio.h>
    _wfopen <stdio.h> or <wchar.h>

    _wfopen is a Microsoft extension. For more information about compatibility, see Compatibility.

    The c, n, t, S, R, T, and D mode options are Microsoft extensions for fopen and _fdopen and shouldn’t be used where ANSI portability is desired.

    Example 1

    The following program opens two files. It uses fclose to close the first file and _fcloseall to close all remaining files.

    // crt_fopen.c
    // compile with: /W3
    // This program opens two files. It uses
    // fclose to close the first file and
    // _fcloseall to close all remaining files.
    
    #include <stdio.h>
    
    FILE *stream, *stream2;
    
    int main( void )
    {
       int numclosed;
    
       // Open for read (will fail if file "crt_fopen.c" does not exist)
       if( (stream  = fopen( "crt_fopen.c", "r" )) == NULL ) // C4996
       // Note: fopen is deprecated; consider using fopen_s instead
          printf( "The file 'crt_fopen.c' was not openedn" );
       else
          printf( "The file 'crt_fopen.c' was openedn" );
    
       // Open for write
       if( (stream2 = fopen( "data2", "w+" )) == NULL ) // C4996
          printf( "The file 'data2' was not openedn" );
       else
          printf( "The file 'data2' was openedn" );
    
       // Close stream if it is not NULL
       if( stream)
       {
          if ( fclose( stream ) )
          {
             printf( "The file 'crt_fopen.c' was not closedn" );
          }
       }
    
       // All other files are closed:
       numclosed = _fcloseall( );
       printf( "Number of files closed by _fcloseall: %un", numclosed );
    }
    The file 'crt_fopen.c' was opened
    The file 'data2' was opened
    Number of files closed by _fcloseall: 1
    

    Example 2

    The following program creates a file (or overwrites one if it exists), in text mode that has Unicode encoding. It then writes two strings into the file and closes the file. The output is a file named _wfopen_test.xml, which contains the data from the output section.

    // crt__wfopen.c
    // compile with: /W3
    // This program creates a file (or overwrites one if
    // it exists), in text mode using Unicode encoding.
    // It then writes two strings into the file
    // and then closes the file.
    
    #include <stdio.h>
    #include <stddef.h>
    #include <stdlib.h>
    #include <wchar.h>
    
    #define BUFFER_SIZE 50
    
    int main(int argc, char** argv)
    {
        wchar_t str[BUFFER_SIZE];
        size_t  strSize;
        FILE*   fileHandle;
    
        // Create an the xml file in text and Unicode encoding mode.
        if ((fileHandle = _wfopen( L"_wfopen_test.xml",L"wt+,ccs=UNICODE")) == NULL) // C4996
        // Note: _wfopen is deprecated; consider using _wfopen_s instead
        {
            wprintf(L"_wfopen failed!n");
            return(0);
        }
    
        // Write a string into the file.
        wcscpy_s(str, sizeof(str)/sizeof(wchar_t), L"<xmlTag>n");
        strSize = wcslen(str);
        if (fwrite(str, sizeof(wchar_t), strSize, fileHandle) != strSize)
        {
            wprintf(L"fwrite failed!n");
        }
    
        // Write a string into the file.
        wcscpy_s(str, sizeof(str)/sizeof(wchar_t), L"</xmlTag>");
        strSize = wcslen(str);
        if (fwrite(str, sizeof(wchar_t), strSize, fileHandle) != strSize)
        {
            wprintf(L"fwrite failed!n");
        }
    
        // Close the file.
        if (fclose(fileHandle))
        {
            wprintf(L"fclose failed!n");
        }
        return 0;
    }

    See also

    Stream I/O
    Interpretation of multibyte-character sequences
    fclose, _fcloseall
    _fdopen, _wfdopen
    ferror
    _fileno
    freopen, _wfreopen
    _open, _wopen
    _setmode
    _sopen, _wsopen

    Понравилась статья? Поделить с друзьями:
  • Fondital victoria compact неисправности ошибки
  • Fmr 3130 ошибка мерседес актрос
  • Fmod64 dll ошибка
  • Fml modloading dupemod ошибка
  • Fml forge ошибка