- What is lseek in linux
- ОПИСАНИЕ
- ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ
- ОШИБКИ
- СООТВЕТСТВИЕ СТАНДАРТАМ
- ОГРАНИЧЕНИЯ
- ЗАМЕЧАНИЯ
- What is lseek in linux
- Перемещения по данным файла и промежутки
- ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ
- ОШИБКИ
- СООТВЕТСТВИЕ СТАНДАРТАМ
- ЗАМЕЧАНИЯ
- lseek(3) — Linux man page
- Prolog
- Synopsis
- Description
- Return Value
- Errors
- Examples
- Application Usage
- Rationale
- Future Directions
- See Also
- lseek(2) — Linux man page
- Synopsis
- Description
- Seeking file data and holes
- Return Value
- Errors
- Conforming to
- Notes
- lseek — устанавливает позицию чтения/записи информации в файле
What is lseek in linux
off_t lseek(int fildes , off_t offset , int whence );
ОПИСАНИЕ
Функция lseek позволяет задавать смещения, которые будут находиться за существующим концом файла (но это не изменяет размер файла). Если позднее по этому смещению будут записаны данные, то последующее чтение в промежутке от конца файла до этого смещения, будет возвращать нулевые байты (пока в этот промежуток не будут фактически записаны данные).
ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ
ОШИБКИ
СООТВЕТСТВИЕ СТАНДАРТАМ
ОГРАНИЧЕНИЯ
Специальные ограничения Linux: при использовании lseek на терминальных устройствах tty возвращается ESPIPE .
ЗАМЕЧАНИЯ
Если вы будете конвертировать старый код, подставляйте вместо значений whence следующие макросы:
old | new |
0 | SEEK_SET |
1 | SEEK_CUR |
2 | SEEK_END |
L_SET | SEEK_SET |
L_INCR | SEEK_CUR |
L_XTND | SEEK_END |
SVR1-3 возвращает long вместо off_t , BSD возвращает int .
Заметим, что файловые дескрипторы, созданные через dup (2) или fork (2) разделяют указатель текущей позиции в файле, так что позиционирование таких файлов может быть выполнено на тех же условиях.
Источник
What is lseek in linux
Функция lseek() позволяет задавать смещение, которое будет находиться за существующим концом файла (но это не изменяет размер файла). Если позднее по этому смещению будут записаны данные, то последующее чтение в промежутке («дырке») от конца файла до этого смещения, будет возвращать нулевые байты (‘\0’), пока в этот промежуток действительно не будут записаны данные.
Перемещения по данным файла и промежутки
В обоих, показанных выше, случаях, lseek() завершится с ошибкой, если offset указывает за конец файла.
Эти операции позволяют приложениям отображать промежутки в разреженно выделенном файле. Это может быть полезно для таких приложений, как инструменты резервного копирования файлов, которые могут выиграть в месте при создании резервных копий и сохранить промежутки, если у них есть механизм их обнаружения.
Для поддержки этих операций промежуток представляется последовательностью нулей, которые (обычно) физически не занимают места на носителе. Однако файловая система может не сообщать о промежутках, поэтому эти операции — не гарантируемый механизм отображения пространства носителя в файл (более того, последовательность нулей, которая на самом деле была записана на носитель, может не посчитаться промежутком). В простейшей реализации, файловая система может поддержать эти операции так: при SEEK_HOLE всегда возвращать смещение конца файла, а при SEEK_DATA всегда возвращать значение offset (т.е., даже если расположение, указанное offset, является промежутком, это можно считать данными, состоящими из последовательности нулей).
Чтобы получить определения SEEK_DATA и SEEK_HOLE из , нужно задать макрос тестирования свойств _GNU_SOURCE.
Операции SEEK_HOLE и SEEK_DATA поддерживаются следующими файловыми системами:
* Btrfs (начиная с Linux 3.1) * OCFS (начиная с Linux 3.2) * XFS (начиная с Linux 3.5) * ext4 (начиная с Linux 3.8) * tmpfs (начиная с Linux 3.8)
ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ
ОШИБКИ
СООТВЕТСТВИЕ СТАНДАРТАМ
Значения SEEK_DATA и SEEK_HOLE являются нестандартными расширениями, которые также есть в Solaris, FreeBSD и DragonFly BSD; их предложили включить в следующую редакцию POSIX (выпуск 8).
ЗАМЕЧАНИЯ
Некоторые устройства не могут выполнять смещения и в POSIX не указано какие устройства должны поддерживать lseek().
В Linux при использовании lseek() на терминальных устройствах возвращается ESPIPE.
Если вы будете конвертировать старый код, используйте вместо значений whence следующие макросы:
старое значение | новое значение |
0 | SEEK_SET |
1 | SEEK_CUR |
2 | SEEK_END |
L_SET | SEEK_SET |
L_INCR | SEEK_CUR |
L_XTND | SEEK_END |
Заметим, что файловые дескрипторы, созданные через dup(2) или fork(2), используют общий указатель на текущее положение в файле, так что позиционирование в таких файлах может приводить к состязательности процессов.
Источник
lseek(3) — Linux man page
Prolog
Synopsis
Description
The lseek() function shall set the file offset for the open file description associated with the file descriptor fildes, as follows: * If whence is SEEK_SET, the file offset shall be set to offset bytes. * If whence is SEEK_CUR, the file offset shall be set to its current location plus offset. * If whence is SEEK_END, the file offset shall be set to the size of the file plus offset.
The symbolic constants SEEK_SET, SEEK_CUR, and SEEK_END are defined in .
The behavior of lseek() on devices which are incapable of seeking is implementation-defined. The value of the file offset associated with such a device is undefined.
The lseek() function shall allow the file offset to be set beyond the end of the existing data in the file. If data is later written at this point, subsequent reads of data in the gap shall return bytes with the value 0 until data is actually written into the gap.
The lseek() function shall not, by itself, extend the size of a file.
If fildes refers to a shared memory object, the result of the lseek() function is unspecified.
If fildes refers to a typed memory object, the result of the lseek() function is unspecified.
Return Value
Upon successful completion, the resulting offset, as measured in bytes from the beginning of the file, shall be returned. Otherwise, (off_t)-1 shall be returned, errno shall be set to indicate the error, and the file offset shall remain unchanged.
Errors
The lseek() function shall fail if: EBADF The fildes argument is not an open file descriptor. EINVAL The whence argument is not a proper value, or the resulting file offset would be negative for a regular file, block special file, or directory. EOVERFLOW The resulting file offset would be a value which cannot be represented correctly in an object of type off_t. ESPIPE The fildes argument is associated with a pipe, FIFO, or socket.
The following sections are informative.
Examples
Application Usage
Rationale
The ISO C standard includes the functions fgetpos() and fsetpos(), which work on very large files by use of a special positioning type.
Although lseek() may position the file offset beyond the end of the file, this function does not itself extend the size of the file. While the only function in IEEE Std 1003.1-2001 that may directly extend the size of the file is write(), truncate(), and ftruncate(), several functions originally derived from the ISO C standard, such as fwrite(), fprintf(), and so on, may do so (by causing calls on write()).
An invalid file offset that would cause [EINVAL] to be returned may be both implementation-defined and device-dependent (for example, memory may have few invalid values). A negative file offset may be valid for some devices in some implementations.
The POSIX.1-1990 standard did not specifically prohibit lseek() from returning a negative offset. Therefore, an application was required to clear errno prior to the call and check errno upon return to determine whether a return value of ( off_t)-1 is a negative offset or an indication of an error condition. The standard developers did not wish to require this action on the part of a conforming application, and chose to require that errno be set to [EINVAL] when the resulting file offset would be negative for a regular file, block special file, or directory.
Future Directions
See Also
open(), the Base Definitions volume of IEEE Std 1003.1-2001, ,
Источник
lseek(2) — Linux man page
Synopsis
Description
The lseek() function allows the file offset to be set beyond the end of the file (but this does not change the size of the file). If data is later written at this point, subsequent reads of the data in the gap (a «hole») return null bytes (aq\0aq) until data is actually written into the gap.
Seeking file data and holes
In both of the above cases, lseek() fails if offset points past the end of the file.
These operations allow applications to map holes in a sparsely allocated file. This can be useful for applications such as file backup tools, which can save space when creating backups and preserve holes, if they have a mechanism for discovering holes.
For the purposes of these operations, a hole is a sequence of zeros that (normally) has not been allocated in the underlying file storage. However, a file system is not obliged to report holes, so these operations are not a guaranteed mechanism for mapping the storage space actually allocated to a file. (Furthermore, a sequence of zeros that actually has been written to the underlying storage may not be reported as a hole.) In the simplest implementation, a file system can support the operations by making SEEK_HOLE always return the offset of the end of the file, and making SEEK_DATA always return offset (i.e., even if the location referred to by offset is a hole, it can be considered to consist of data that is a sequence of zeros).
Return Value
Errors
Conforming to
SEEK_DATA and SEEK_HOLE are nonstandard extensions also present in Solaris, FreeBSD, and DragonFly BSD; they are proposed for inclusion in the next POSIX revision (Issue 8).
Notes
On Linux, using lseek() on a terminal device returns ESPIPE.
When converting old code, substitute values for whence with the following macros:
old | new |
0 | SEEK_SET |
1 | SEEK_CUR |
2 | SEEK_END |
L_SET | SEEK_SET |
L_INCR | SEEK_CUR |
L_XTND | SEEK_END |
Note that file descriptors created by dup(2) or fork(2) share the current file position pointer, so seeking on such files may be subject to race conditions.
Источник
lseek — устанавливает позицию чтения/записи информации в файле
НАЗВАНИЕ
lseek — устанавливает позицию чтения/записи информации в
файле
СИНТАКСИС
#include
#include
off_t lseek(int fildes, off_t offset, int whence);
ОПИСАНИЕ
Функция lseek устанавливает аргумент файлового описателя
fildes равным offset в соответствии с директивой whence
следующим образом:
SEEK_SET
(смещение offset устанавливается в байтах);
SEEK_CUR
(к текущему значению смещения добавляется offset
байтов);
SEEK_END
(смещение будет равно размеру файла плюс offset
байтов);
(функция lseek позволяет устанавливать позицию файла за
пределами самого файла. Если в дальнейшем будут записаны
данные этого смещения, то чтение в промежутке вернет
последовательность из нулевых байтов).
ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ
При успешном завершении lseek возвращает новое смещение в
байтах от начала файла. В противном случае возвращается
значение (off_t)-1 и
переменная errno устанавливается должным образом.
КОДЫ ОШИБОК
EBADF Fildes не является открытым файловым описателем.
ESPIPE Fildes ассоциирован с каналом, сокетом или каналом
FIFO.
EINVAL Whence не имеет разрешенного значения.
СООТВЕТСТВИЕ СТАНДАРТАМ
SVr4, POSIX, BSD 4.3
ОГРАНИЧЕНИЯ
Некоторые устройства не поддерживают изменение позиции в
файле, а стандарт POSIX не указывает, какие устройства
должны поддерживать эту операцию. Ограничения,
специфичные для Linux: использование lseek на устройстве
tty возвращает ESPIPE. Другие системы возвращают
количество записанных символов, используя SEEK_SET для
установки счетчика. Некоторые устройства (например,
/dev/null) не приводят к ошибке ESPIPE, но возвращают
указатель с неопределенным значением.
ЗАМЕЧАНИЯ
Использование слова whence в этом документе не является
корректным с точки зрения английского языка, но
сохраняется в силу исторических причин. При
преобразовании старого кода заменяйте значения whence
следующими макросами:
старое новое
0 SEEK_SET
1 SEEK_CUR
2 SEEK_END
L_SET SEEK_SET
L_INCR SEEK_CUR
L_XTND SEEK_END
SVR1-3 возвращает long вместо off_t, а BSD возвращает int.
Заметим, что описатели файла, соданные dup(2) или fork(2),
разделяют указатель текущего положения в файле, поэтому
поиск по таким файлам будет похож на гонку.
Источник