Fopen error codes

C++ Documentation. Contribute to MicrosoftDocs/cpp-docs development by creating an account on GitHub.
title description ms.date api_name api_location api_type topic_type f1_keywords helpviewer_keywords

fopen_s, _wfopen_s

Describes the API for `fopen_s` and `_wfopen_s`

05/18/2022

_wfopen_s

fopen_s

_o__wfopen_s

_o_fopen_s

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_s

CORECRT_WSTDIO/_wfopen_s

TCHAR/_tfopen_s

fopen_s

_wfopen_s

_tfopen_s

_wfopen_s function

opening files, for file I/O

_tfopen_s function

tfopen_s function

wfopen_s function

fopen_s function

Unicode [C++], creating files

Unicode [C++], writing files

files [C++], opening

Unicode [C++], files

fopen_s, _wfopen_s

Opens a file. These versions of fopen, _wfopen have security enhancements, as described in Security features in the CRT.

Syntax

errno_t fopen_s(
   FILE** pFile,
   const char *filename,
   const char *mode
);
errno_t _wfopen_s(
   FILE** pFile,
   const wchar_t *filename,
   const wchar_t *mode
);

Parameters

pFile
A pointer to the file pointer that will receive the pointer to the opened file.

filename
Filename.

mode
Type of access permitted.

Return value

Zero if successful; an error code on failure. For more information about these error codes, see errno, _doserrno, _sys_errlist, and _sys_nerr.

Error conditions

pFile filename mode Return Value Contents of pFile
NULL any any EINVAL unchanged
any NULL any EINVAL unchanged
any any NULL EINVAL unchanged

Remarks

The fopen_s and _wfopen_s functions can’t open a file for sharing. If you need to share the file, use _fsopen or _wfsopen with the appropriate sharing mode constant—for example, use _SH_DENYNO for read/write sharing.

The fopen_s function opens the file that’s specified by filename. _wfopen_s is a wide-character version of fopen_s; the arguments to _wfopen_s are wide-character strings. _wfopen_s and fopen_s behave identically otherwise.

fopen_s accepts paths that are valid on the file system at the point of execution; UNC paths and paths that involve mapped network drives are accepted by fopen_s as long as the system that’s executing the code has access to the share or mapped network drive at the time of execution. When you construct paths for fopen_s, don’t make assumptions about the availability of drives, paths, or network shares in the execution environment. You can use either forward slashes (/) or backslashes () as the directory separators in a path.

These functions validate their parameters. If pFile, filename, or mode is a null pointer, these functions generate an invalid parameter exception, as described in Parameter validation.

Always check the return value to see if the function succeeded before you do any further operations on the file. If an error occurs, the error code is returned, and the global variable errno is set. 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_s supports Unicode file streams. To open a new or existing Unicode file, pass a ccs flag that specifies the desired encoding to fopen_s, for example:

fopen_s(&fp, "newfile.txt", "w+, ccs=UNICODE");

Allowed values of the ccs flag are UNICODE, UTF-8, and UTF-16LE. If no value is specified for ccs, fopen_s uses ANSI encoding.

If the file already exists and is opened for reading or appending, the byte order mark (BOM), if present in the file, determines the encoding. The BOM encoding takes precedence over the encoding that’s specified by the ccs flag. The ccs encoding is only used when no BOM is present or if 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 for various ccs flag values that are given to fopen_s and for BOMs 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-8 UTF-8 UTF-16LE
UTF-8 UTF-8 UTF-8 UTF-16LE
UTF-16LE UTF-16LE UTF-8 UTF-16LE

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

If mode is "a, ccs=UNICODE", "a, ccs=UTF-8", or "a, ccs=UTF-16LE", fopen_s first tries to open the file with both read access and write access. If successful, the function reads the BOM to determine the encoding for the file; if unsuccessful, the function uses the default encoding for the file. In either case, fopen_s then reopens the file with write-only access. (This behavior applies to a mode only, not a+.)

The character string mode specifies the kind of access that’s 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_s 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" or "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 it’s always moved back to the end of the file before any write operation is carried out so that existing data can’t be overwritten.

The "a" mode doesn’t remove the EOF marker before appending 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 that’s appended to the file. The "a+" mode does remove the EOF marker before appending to the file. 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 allowed. (The file is said to be open for «update».) However, when you switch from reading to writing, the input operation must come across an EOF marker. If there’s no EOF marker, 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.

Starting in C11, you can append "x" to "w" or "w+" to cause the function fail if the file exists, instead of overwriting it.

In addition to the values above, the following characters can be included in mode to specify the translation mode for newline characters:

mode modifier Translation mode
t Open in text (translated) mode.
b Open in binary (untranslated) mode; translations involving carriage-return and line feed characters are suppressed.

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

Also, 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. 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 using 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.

mode modifier Behavior
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 as temporary. If possible, it isn’t flushed to disk.
D Specifies a file as temporary. It’s deleted when the last file pointer is closed.
ccs=UNICODE Specifies UNICODE as the encoded character set to use for this file. Leave unspecified if you want ANSI encoding.
ccs=UTF-8 Specifies UTF-8 as the encoded character set to use for this file. Leave unspecified if you want ANSI encoding.
ccs=UTF-16LE Specifies UTF-16LE as the encoded character set to use for this file. Leave unspecified if you want ANSI encoding.

Valid characters for the mode string used in fopen_s and _fdopen correspond to oflag arguments 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
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

The c, n, and t mode options are Microsoft extensions for fopen_s and _fdopen and shouldn’t be used where you want ANSI portability.

If you’re using rb mode, memory mapped Win32 files might also be an option if you don’t need to port your code, you expect to read much of the file, or you don’t care about network performance.

Requirements

Function Required header C++ header
fopen_s <stdio.h> <cstdio>
_wfopen_s <stdio.h> or <wchar.h> <cstdio>

For more information on standards conformance and naming conventions in the C runtime library, see Compatibility.

Generic-text routine mappings

<tchar.h> routine _UNICODE and _MBCS not defined _MBCS defined _UNICODE defined
_tfopen_s fopen_s fopen_s _wfopen_s

Libraries

All versions of the C run-time libraries.

Example

// crt_fopen_s.c
// 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 )
{
   errno_t err;

   // Open for read (will fail if file "crt_fopen_s.c" doesn't exist)
   err  = fopen_s( &stream, "crt_fopen_s.c", "r" );
   if( err == 0 )
   {
      printf( "The file 'crt_fopen_s.c' was openedn" );
   }
   else
   {
      printf( "The file 'crt_fopen_s.c' was not openedn" );
   }

   // Open for write
   err = fopen_s( &stream2, "data2", "w+, ccs=UTF-8" );
   if( err == 0 )
   {
      printf( "The file 'data2' was openedn" );
   }
   else
   {
      printf( "The file 'data2' was not openedn" );
   }

   // Close stream if it isn't NULL
   if( stream )
   {
      err = fclose( stream );
      if ( err == 0 )
      {
         printf( "The file 'crt_fopen_s.c' was closedn" );
      }
      else
      {
         printf( "The file 'crt_fopen_s.c' was not closedn" );
      }
   }

   // All other files are closed:
   int numclosed = _fcloseall( );
   printf( "Number of files closed by _fcloseall: %un", numclosed );
}
The file 'crt_fopen_s.c' was opened
The file 'data2' was opened
Number of files closed by _fcloseall: 1

See also

Stream I/O
fclose, _fcloseall
_fdopen, _wfdopen
ferror
_fileno
freopen, _wfreopen
_open, _wopen
_setmode

ОБЗОР

#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=строка не указан, то
широкосимвольность потока определяется по первой файловой операции. Если это
операция является широкосимвольной, то поток помечается как широкосимвольный
и загружаются функции для перекодировки.

Определено в заголовке <stdio.h>
(1)
FILE *fopen( const char *filename, const char *mode );
(until C99)
FILE *fopen( const char *restrict filename, const char *restrict mode );
(since C99)
errno_t fopen_s( FILE *restrict *restrict streamptr,
                 const char *restrict filename,
                 const char *restrict mode );
(2) (since C11)

1) Открывает файл, указанный в filename и возвращает указатель на поток файлов, связанный с этим файлом. mode используется для определения режима доступа к файлу.

2) То же, что и (1), за исключением того, что указатель на файловый поток записывается в streamptr , и во время выполнения обнаруживаются следующие ошибки, при которых вызывается установленная в настоящее время функция обработчика ограничения :

  • streamptr — нулевой указатель
  • filename является нулевым указателем
  • mode является нулевым указателем
Как и все функции с проверкой границ, fopen_s гарантированно доступна только в том случае, если __STDC_LIB_EXT1__ определен реализацией и если пользователь определяет __STDC_WANT_LIB_EXT1__ целочисленной константой 1 перед включением <stdio.h> .

Parameters

filename имя файла,чтобы связать поток файлов с
mode символьная строка с завершающим нулем, определяющая режим доступа к файлу
streamptr указатель на указатель,где функция хранит результат (внешний параметр)

Флаги доступа к файлам

File access
mode string
Meaning Explanation Действие,если файл
already exists
Действие,если файл
не существует
"r" read Открыть файл для чтения считывание с начала неудача в открытии
"w" write Создать файл для записи destroy contents create new
"a" append Добавить в файл писать до конца create new
"r+" read extended Открыть файл для чтения/записи считывание с начала error
"w+" write extended Создать файл для чтения/записи destroy contents create new
"a+" append extended Открыть файл для чтения/записи писать до конца create new
При желании можно указать флаг режима доступа к файлу "b" чтобы открыть файл в двоичном режиме. Этот флаг не влияет на системы POSIX, но в Windows он отключает специальную обработку 'n' и 'x1A' .
В режимах доступа к файлам приложения данные записываются в конец файла независимо от текущего положения индикатора положения файла.
Поведение не определено, если режим не является одной из строк, перечисленных выше. Некоторые реализации определяют дополнительные поддерживаемые режимы (например, Windows ).
В режиме обновления ( '+' ) могут выполняться как ввод, так и вывод, но за выводом не может следовать ввод без промежуточного вызова fflush , fseek , fsetpos или rewind , а за вводом не может следовать вывод без промежуточного вызова fseek , fsetpos или rewind , если операция ввода не встретила конец файла. В режиме обновления реализациям разрешено использовать двоичный режим, даже если указан текстовый режим.
Флаг режима доступа к файлу "x" может быть дополнительно добавлен к спецификаторам "w" или "w+" .Этот флаг вызывает сбой функции, если файл существует, вместо его перезаписи. (С11)
При использовании fopen_s или freopen_s разрешения на доступ к любому файлу, созданному с помощью "w" или "a" не позволяют другим пользователям получить к нему доступ. Флаг режима доступа к файлу "u" может быть дополнительно добавлен к любому спецификатору, который начинается с "w" или "a" fopen по умолчанию . (С11)

Return value

1) В случае успеха возвращает указатель на новый файловый поток. Поток полностью буферизуется, если filename относится к интерактивному устройству. В случае ошибки возвращает null pointer . POSIX требует, чтобы в этом случае было установлено значение errno .

2) В случае успеха возвращает ноль и указатель на новый файловый поток записывается в *streamptr . При ошибке возвращает ненулевой код ошибки и записывает нулевой указатель в *streamptr (если только streamptr не является нулевым указателем).

Notes

Формат имени filename определяется реализацией и не обязательно относится к файлу (например, это может быть консоль или другое устройство, доступное через API файловой системы). На платформах, которые их поддерживают, filename может содержать абсолютный или относительный путь файловой системы.

Example

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    int is_ok = EXIT_FAILURE;
    const char* fname = "/tmp/unique_name.txt"; 
    FILE* fp = fopen(fname, "w+");
    if(!fp) {
        perror("File opening failed");
        return is_ok;
    }
    fputs("Hello, world!n", fp);
    rewind(fp);
 
    int c; 
    while ((c = fgetc(fp)) != EOF) { 
       putchar(c);
    }
 
    if (ferror(fp)) {
        puts("I/O error when reading");
    } else if (feof(fp)) {
        puts("End of file reached successfully");
        is_ok = EXIT_SUCCESS;
    }
 
    fclose(fp);
    remove(fname);
    return is_ok;
}

Possible output:

Hello, world!
End of file reached successfully

References

  • Стандарт С17 (ISO/IEC 9899:2018):
    • 7.21.5.3 Функция fopen (p:223-224)
    • K.3.5.2.1 Функция fopen_s (p:428-429)
  • Стандарт C11 (ISO/IEC 9899:2011):
    • 7.21.5.3 Функция открытия (стр.305-306)
    • K.3.5.2.1 Функция fopen_s (стр.588-590)
  • Стандарт С99 (ISO/IEC 9899:1999):
    • 7.19.5.3 Функция открытия (стр.271-272)
  • Стандарт C89/C90 (ISO/IEC 9899:1990):
    • 4.9.5.3 Функция отпирания

See also


C

  • fgetws

  • FILE

  • fpos_t

  • printf, fprintf, sprintf, snprintf, printf_s, fprintf_s, sprintf_s, snprintf_s

fopen, fopen_s

Defined in header <stdio.h>
(1)
FILE *fopen( const char *filename, const char *mode );
(until C99)
FILE *fopen( const char *restrict filename, const char *restrict mode );
(since C99)
errno_t fopen_s( FILE *restrict *restrict streamptr,
                 const char *restrict filename,
                 const char *restrict mode );
(2) (since C11)

1) Opens a file indicated by filename and returns a pointer to the file stream associated with that file. mode is used to determine the file access mode.

2) Same as (1), except that the pointer to the file stream is written to streamptr and the following errors are detected at runtime and call the currently installed constraint handler function:

  • streamptr is a null pointer
  • filename is a null pointer
  • mode is a null pointer
As with all bounds-checked functions, fopen_s is only guaranteed to be available if __STDC_LIB_EXT1__ is defined by the implementation and if the user defines __STDC_WANT_LIB_EXT1__ to the integer constant 1 before including <stdio.h>.

Parameters

filename file name to associate the file stream to
mode null-terminated character string determining file access mode
streamptr pointer to a pointer where the function stores the result (an out-parameter)

File access flags

File access
mode string
Meaning Explanation Action if file
already exists
Action if file
does not exist
"r" read Open a file for reading read from start failure to open
"w" write Create a file for writing destroy contents create new
"a" append Append to a file write to end create new
"r+" read extended Open a file for read/write read from start error
"w+" write extended Create a file for read/write destroy contents create new
"a+" append extended Open a file for read/write write to end create new
File access mode flag "b" can optionally be specified to open a file in binary mode. This flag has no effect on POSIX systems, but on Windows it disables special handling of 'n' and 'x1A'.
On the append file access modes, data is written to the end of the file regardless of the current position of the file position indicator.
The behavior is undefined if the mode is not one of the strings listed above. Some implementations define additional supported modes (e.g. Windows).
In update mode ('+'), both input and output may be performed, but output cannot be followed by input without an intervening call to fflush, fseek, fsetpos or rewind, and input cannot be followed by output without an intervening call to fseek, fsetpos or rewind, unless the input operation encountered end of file. In update mode, implementations are permitted to use binary mode even when text mode is specified.
File access mode flag "x" can optionally be appended to "w" or "w+" specifiers. This flag forces the function to fail if the file exists, instead of overwriting it. (C11)
When using fopen_s or freopen_s, file access permissions for any file created with "w" or "a" prevents other users from accessing it. File access mode flag "u" can optionally be prepended to any specifier that begins with "w" or "a", to enable the default fopen permissions. (C11)

Return value

1) If successful, returns a pointer to the new file stream. The stream is fully buffered unless filename refers to an interactive device. On error, returns a null pointer. POSIX requires that errno be set in this case.

2) If successful, returns zero and a pointer to the new file stream is written to *streamptr. On error, returns a non-zero error code and writes the null pointer to *streamptr (unless streamptr is a null pointer itself).

Notes

The format of filename is implementation-defined, and does not necessarily refer to a file (e.g. it may be the console or another device accessible though filesystem API). On platforms that support them, filename may include absolute or relative filesystem path.

Example

#include <stdio.h>
#include <stdlib.h>
 
int main(void)
{
    int is_ok = EXIT_FAILURE;
    const char* fname = "/tmp/unique_name.txt"; // or tmpnam(NULL);
    FILE* fp = fopen(fname, "w+");
    if(!fp) {
        perror("File opening failed");
        return is_ok;
    }
    fputs("Hello, world!n", fp);
    rewind(fp);
 
    int c; // note: int, not char, required to handle EOF
    while ((c = fgetc(fp)) != EOF) { // standard C I/O file reading loop
       putchar(c);
    }
 
    if (ferror(fp)) {
        puts("I/O error when reading");
    } else if (feof(fp)) {
        puts("End of file reached successfully");
        is_ok = EXIT_SUCCESS;
    }
 
    fclose(fp);
    remove(fname);
    return is_ok;
}

Possible output:

Hello, world!
End of file reached successfully

References

  • C17 standard (ISO/IEC 9899:2018):
    • 7.21.5.3 The fopen function (p: 223-224)
    • K.3.5.2.1 The fopen_s function (p: 428-429)
  • C11 standard (ISO/IEC 9899:2011):
    • 7.21.5.3 The fopen function (p: 305-306)
    • K.3.5.2.1 The fopen_s function (p: 588-590)
  • C99 standard (ISO/IEC 9899:1999):
    • 7.19.5.3 The fopen function (p: 271-272)
  • C89/C90 standard (ISO/IEC 9899:1990):
    • 4.9.5.3 The fopen function

See also

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

fopen (3)


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

    NAME

    fopen - open a stream
     
    

    SYNOPSIS

    #include <stdio.h>
    
    FILE *fopen(const char *filename, const char *mode);
    

    DESCRIPTION

    The fopen() function opens the file whose pathname is the string pointed to by filename, and associates a stream with it.

    The argument mode points to a string beginning with one of the following sequences:

    r or rb

    Open file for reading.

    w or wb

    Truncate to zero length or create file for writing.

    a or ab

    Append; open or create file for writing at end-of-file.

    r+ or rb+ or r+b

    Open file for update (reading and writing).

    w+ or wb+ or w+b

    Truncate to zero length or create file for update.

    a+ or ab+ or a+b

    Append; open or create file for update, writing at end-of-file.

    The character b has no effect, but is allowed for ISO C standard conformance (see standards(5)). Opening a file with read
    mode (r as the first character in the mode argument) fails if the file does not exist or cannot be read.

    Opening a file with append mode (a as the first character in the mode argument) causes all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to fseek(3C). If two separate processes open the same file for append, each process may write freely to the file without fear of destroying output being written by the other. The output from the two processes will be intermixed in the file in the
    order in which it is written.

    When a file is opened with update mode (+ as the second or third character in the mode argument), both input and output may be performed on the associated stream. However, output must not be directly followed by input without an intervening call to fflush(3C) or to a file positioning function ( fseek(3C), fsetpos(3C) or rewind(3C)), and input must not be directly followed by output without an intervening call to a file
    positioning function, unless the input operation encounters end-of-file.

    When opened, a stream is fully buffered if and only if it can be determined not to refer to an interactive device. The error and end-of-file indicators for the stream are cleared.

    If mode begins with w or a and the file did not previously exist, upon successful completion, fopen() function will mark for update the st_atime, st_ctime and st_mtime fields of the file and the st_ctime and st_mtime fields of the parent directory.

    If mode begins with w and the file did previously exist, upon successful completion, fopen() will mark for update the st_ctime and st_mtime fields of the file. The fopen() function
    will allocate a file descriptor as open(2) does.

    Normally, 32-bit applications return an EMFILE error when attempting to associate a stream with a file accessed by a file descriptor with a value greater than 255. If the last character of mode is F, 32-bit applications will be allowed
    to associate a stream with a file accessed by a file descriptor with a value greater than 255. A FILE pointer obtained in this way must never be used by any code that might directly access fields in the FILE structure. If the fields in the FILE
    structure are used directly by 32-bit applications when the last character of mode is F, data corruption could occur. See the USAGE section of this manual page and the enable_extended_FILE_stdio(3C) manual page for other options for enabling the extended FILE facility.

    In 64-bit applications, the last character of mode is silently ignored if it is F. 64-bit applications are always allowed to associate a stream with a file accessed by a file descriptor with any value.

    The largest value that can be represented correctly in an object of type off_t will be established as the offset maximum in the open file description.
     

    RETURN VALUES

    Upon successful completion, fopen() returns a pointer to the object controlling the stream. Otherwise, a null pointer is returned and errno is set to indicate the error.

    The fopen() function may fail and not set errno if there are no free stdio streams.
     

    ERRORS

    The fopen() function will fail if:

    EACCES

    Search permission is denied on a component of the path prefix, or the file exists and the permissions specified by mode are denied, or the file does not exist and write permission is denied for the
    parent directory of the file to be created.

    EINTR

    A signal was caught during the execution of fopen().

    EISDIR

    The named file is a directory and mode requires write access.

    ELOOP

    Too many symbolic links were encountered in resolving path.

    EMFILE

    There are {OPEN_MAX} file descriptors currently open in the calling process.

    ENAMETOOLONG

    The length of the filename exceeds PATH_MAX or a pathname component is longer than NAME_MAX.

    ENFILE

    The maximum allowable number of files is currently open in the system.

    ENOENT

    A component of filename does not name an existing file or filename is an empty string.

    ENOSPC

    The directory or file system that would contain the new file cannot be expanded, the file does not exist, and it was to be created.

    ENOTDIR

    A component of the path prefix is not a directory.

    ENXIO

    The named file is a character special or block special file, and the device associated with this special file does not exist.

    EOVERFLOW

    The current value of the file position cannot be represented correctly in an object of type fpos_t.

    EROFS

    The named file resides on a read-only file system and mode requires write access.

    The fopen() function may fail if:

    EINVAL

    The value of the mode argument is not valid.

    EMFILE

    {FOPEN_MAX} streams are currently open in the calling process.

    {STREAM_MAX} streams are currently open in the calling process.

    ENAMETOOLONG

    Pathname resolution of a symbolic link produced an intermediate result whose length exceeds {PATH_MAX}.

    ENOMEM

    Insufficient storage space is available.

    ETXTBSY

    The file is a pure procedure (shared text) file that is being executed and mode requires write access.

    USAGE

    A process is allowed to have at least {FOPEN_MAX} stdio streams open at a time. For 32-bit applications, however, the underlying ABIs formerly required that no file descriptor used to access the file underlying a stdio stream have a value
    greater than 255. To maintain binary compatibility with earlier Solaris releases, this limit still constrains 32-bit applications. However, when a 32-bit application is aware that no code that has access to the FILE pointer returned by fopen() will use the FILE pointer to directly access any fields in the FILE structure, the F character can be used as the last character in the mode argument to circumvent this limit. Because it could lead to data corruption, the F
    character in mode must never be used when the FILE pointer might later be used by binary code unknown to the user. The F character in mode is intended to be used by library functions that need a FILE pointer to access data to process a user request, but do not need to pass the FILE pointer back to the user. 32-bit applications that have been inspected can use the extended FILE facility to circumvent this limit if the inspection shows that no FILE pointers will be used to directly access FILE structure contents.

    The fopen() function has a transitional interface for 64-bit file offsets. See lf64(5).
     

    ATTRIBUTES

    See attributes(5) for descriptions of the following attributes:

    ATTRIBUTE TYPE ATTRIBUTE VALUE

    Interface Stability See below.

    MT-Level

    The F character in the mode argument is Evolving. In all other respects this function is Standard.
     

    SEE ALSO

    enable_extended_FILE_stdio(3C), fclose(3C), fdopen(3C), fflush(3C), freopen(3C), fsetpos(3C), rewind(3C), attributes(5), lf64(5), standards(5)


     

    Index

    NAME
    SYNOPSIS
    DESCRIPTION
    RETURN VALUES
    ERRORS
    USAGE
    ATTRIBUTES
    SEE ALSO

    Понравилась статья? Поделить с друзьями:

    Читайте также:

  • Ffr 00697 04 ошибка man tga
  • Football manager 2023 application error
  • Ffr 00647 10 ошибка man
  • Ffr 00639 04 ошибка ман
  • Ffr 00171 06 ошибка ман тга

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии