Fopen linux c example

Fopen linux c example

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 );

ОПИСАНИЕ

Параметр 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 при ошибках устанавливают значение errno равным какому-либо значению из определенных в malloc (3).

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

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

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

Источник

Fopen linux c example

FILE *fopen(const char *restrict filename , const char *restrict mode );

DESCRIPTION

The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of IEEE Std 1003.1-2001 defers to the ISO C standard.

Читайте также:  Как создать бэкдор kali linux

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

The mode argument points to a string. If the string is one of the following, the file shall be opened in the indicated mode. Otherwise, the behavior is undefined. 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’ shall have no effect, but is allowed for ISO C standard conformance. Opening a file with read mode ( r as the first character in the mode argument) shall fail 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) shall cause all subsequent writes to the file to be forced to the then current end-of-file, regardless of intervening calls to fseek ().

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, the application shall ensure that output is not directly followed by input without an intervening call to fflush () or to a file positioning function ( fseek (), fsetpos (), or rewind ()), and input is not 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 shall be cleared.

If mode is w , wb , a , ab , w +, wb +, w + b , a +, ab +, or a + b , and the file did not previously exist, upon successful completion, the fopen () function shall 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 is w , wb , w +, wb +, or w + b , and the file did previously exist, upon successful completion, fopen () shall mark for update the st_ctime and st_mtime fields of the file. The fopen () function shall allocate a file descriptor as open () does.

After a successful call to the fopen () function, the orientation of the stream shall be cleared, the encoding rule shall be cleared, and the associated mbstate_t object shall be set to describe an initial conversion state.

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

RETURN VALUE

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

ERRORS

The fopen () function shall 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 fopen (). EISDIR The named file is a directory and mode requires write access. ELOOP A loop exists in symbolic links encountered during resolution of the path argument. EMFILE file descriptors are currently open in the calling process. ENAMETOOLONG

The length of the filename argument exceeds or a pathname component is longer than . 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 the file 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 named file is a regular file and the size of the file cannot be represented correctly in an object of type off_t . EROFS The named file resides on a read-only file system and mode requires write access.

Читайте также:  Современный linux для слабого компьютера

The fopen () function may fail if: EINVAL The value of the mode argument is not valid. ELOOP More than symbolic links were encountered during resolution of the path argument. EMFILE streams are currently open in the calling process. EMFILE streams are currently open in the calling process. ENAMETOOLONG

Pathname resolution of a symbolic link produced an intermediate result whose length exceeds . 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.

The following sections are informative.

EXAMPLES


Opening a File

The following example tries to open the file named file for reading. The fopen () function returns a file pointer that is used in subsequent fgets () and fclose () calls. If the program cannot open the file, it just ignores it.

APPLICATION USAGE


RATIONALE


FUTURE DIRECTIONS


SEE ALSO

fclose () , fdopen () , freopen () , the Base Definitions volume of IEEE Std 1003.1-2001,

Источник

C fopen() function with Examples

Pre-requisite: Basics of File Handling in C
The fopen() method in C is a library function that is used to open a file to perform various operations which include reading, writing etc. along with various modes. If the file exists then the particular file is opened else a new file is created.

Syntax:

Parameters: The method accepts two parameters of character type:

  1. file_name: This is of C string type and accepts the name of the file that is needed to be opened.
  2. mode_of_operation: This is also of C string type and refers to the mode of the file access. Below are the file access modes for C:
    1. “r” – Searches file. Opens the file for reading only. If the file is opened successfully fopen() loads it into memory and sets up a pointer which points to the first character in it. If the file cannot be opened fopen() returns NULL.
    2. “w” – Searches file. If the file exists already, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. It creates a new file for writing only(no reading).
    3. “a” – Searches file. If the file is opened successfully fopen() loads it into memory and sets up a pointer that points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened only for appending(writing at end of file).
    4. “r+” – Searches file. Opens the file for both reading and writing. If opened successfully, fopen() loads it into memory and sets up a pointer which points to the first character in it. Returns NULL, if unable to open the file.
    5. “w+” – Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The difference between w and w+ is that we can also read the file created using w+.
    6. “a+” – Searches file. If the file is opened successfully fopen( ) loads it into memory and sets up a pointer which points to the last character in it. If the file doesn’t exist, a new file is created. Returns NULL, if unable to open the file. The file is opened for reading and appending(writing at end of file).

Return Value: The function is used to return a pointer to FILE if the execution succeeds else NULL is returned.

Источник

Fopen linux c example

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

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

ОПИСАНИЕ

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

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

Читайте также:  Сколько времени может обновляться windows 10

Строка 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) приводит к тому, что все последующие операции записи в этот поток производятся в конец файла, как если бы перед ними была вызвана:

Функция 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() могут также завершаться с ошибками и устанавливают значение 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)

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

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

ЗАМЕЧАНИЯ

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

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

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

Источник

Оцените статью