Класс basic_filebufbasic_filebuf Class
Описывает буфер потока, управляющий передачей элементов типа Char_T, признаки символов которых определяются классом tr, в последовательность элементов, хранящуюся во внешнем файле, и из нее.Describes a stream buffer that controls the transmission of elements of type Char_T, whose character traits are determined by the class Tr, to and from a sequence of elements stored in an external file.
СинтаксисSyntax
template <class Char_T, class Tr = char_traits<Char_T>>
class basic_filebuf : public basic_streambuf<Char_T, Tr>
ПараметрыParameters
Char_TChar_T
Базовый элемент буфера файла.The basic element of the file buffer.
ТСTr
Признаки базового элемента буферного файла (обычно char_traits<Char_T>
).The traits of the basic element of the file buffer (usually char_traits<Char_T>
).
КомментарииRemarks
Шаблон класса описывает буфер потока, который управляет передачей элементов типа Char_T, признаки символов которых определяются классом tr, в последовательность элементов, хранящуюся во внешнем файле, и из нее.The class template describes a stream buffer that controls the transmission of elements of type Char_T, whose character traits are determined by the class Tr, to and from a sequence of elements stored in an external file.
Примечание
Объекты типа basic_filebuf
создаются с внутренним буфером типа char * независимо от char_type
заданного параметром типа Char_T.Objects of type basic_filebuf
are created with an internal buffer of type char* regardless of the char_type
specified by the type parameter Char_T. Это означает, что строка в Юникоде (содержащая wchar_t
символы) будет преобразована в строку ANSI (содержащая char
символы) перед записью во внутренний буфер.This means that a Unicode string (containing wchar_t
characters) will be converted to an ANSI string (containing char
characters) before it is written to the internal buffer. Чтобы сохранить строки Юникода в буфере, создайте новый буфер типа wchar_t
и задайте его с помощью basic_streambuf::pubsetbuf
()
метода.To store Unicode strings in the buffer, create a new buffer of type wchar_t
and set it using the basic_streambuf::pubsetbuf
()
method. Ниже приведен пример, демонстрирующий такие действия.To see an example that demonstrates this behavior, see below.
Объект класса basic_filebuf<Char_T, Tr>
хранит указатель на файл, который обозначает FILE
объект, управляющий потоком, связанным с открытым файлом.An object of class basic_filebuf<Char_T, Tr>
stores a file pointer, which designates the FILE
object that controls the stream associated with an open file. Он также содержит указатели на два аспекта преобразования файла для использования защищенными функциями-членами overflow и underflow.It also stores pointers to two file conversion facets for use by the protected member functions overflow and underflow. Дополнительные сведения см. на веб-сайте basic_filebuf::open
.For more information, see basic_filebuf::open
.
ПримерExample
Следующий пример демонстрирует способ использования объекта типа basic_filebuf<wchar_t>
для хранения символов Юникода в своем внутреннем буфере, с помощью метода pubsetbuf()
.The following example demonstrates how to force an object of type basic_filebuf<wchar_t>
to store Unicode characters in its internal buffer by calling the pubsetbuf()
method.
// unicode_basic_filebuf.cpp
// compile with: /EHsc
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include <memory.h>
#include <string.h>
#define IBUFSIZE 16
using namespace std;
void hexdump(const string& filename);
int main()
{
wchar_t* wszHello = L"Hello World";
wchar_t wBuffer[128];
basic_filebuf<wchar_t> wOutFile;
// Open a file, wcHello.txt, then write to it, then dump the
// file's contents in hex
wOutFile.open("wcHello.txt",
ios_base::out | ios_base::trunc | ios_base::binary);
if(!wOutFile.is_open())
{
cout << "Error Opening wcHello.txt\n";
return -1;
}
wOutFile.sputn(wszHello, (streamsize)wcslen(wszHello));
wOutFile.close();
cout << "Hex Dump of wcHello.txt - note that output is ANSI chars:\n";
hexdump(string("wcHello.txt"));
// Open a file, wwHello.txt, then set the internal buffer of
// the basic_filebuf object to be of type wchar_t, then write
// to the file and dump the file's contents in hex
wOutFile.open("wwHello.txt",
ios_base::out | ios_base::trunc | ios_base::binary);
if(!wOutFile.is_open())
{
cout << "Error Opening wwHello.txt\n";
return -1;
}
wOutFile.pubsetbuf(wBuffer, (streamsize)128);
wOutFile.sputn(wszHello, (streamsize)wcslen(wszHello));
wOutFile.close();
cout << "\nHex Dump of wwHello.txt - note that output is wchar_t chars:\n";
hexdump(string("wwHello.txt"));
return 0;
}
// dump contents of filename to stdout in hex
void hexdump(const string& filename)
{
fstream ifile(filename.c_str(),
ios_base::in | ios_base::binary);
char *ibuff = new char[IBUFSIZE];
char *obuff = new char[(IBUFSIZE*2)+1];
int i;
if(!ifile.is_open())
{
cout << "Cannot Open " << filename.c_str()
<< " for reading\n";
return;
}
if(!ibuff || !obuff)
{
cout << "Cannot Allocate buffers\n";
ifile.close();
return;
}
while(!ifile.eof())
{
memset(obuff,0,(IBUFSIZE*2)+1);
memset(ibuff,0,IBUFSIZE);
ifile.read(ibuff,IBUFSIZE);
// corner case where file is exactly a multiple of
// 16 bytes in length
if(ibuff[0] == 0 && ifile.eof())
break;
for(i = 0; i < IBUFSIZE; i++)
{
if(ibuff[i] >= ' ')
obuff[i] = ibuff[i];
else
obuff[i] = '.';
cout << setfill('0') << setw(2) << hex
<< (int)ibuff[i] << ' ';
}
cout << " " << obuff << endl;
}
ifile.close();
}
Hex Dump of wcHello.txt - note that output is ANSI chars:
48 65 6c 6c 6f 20 57 6f 72 6c 64 00 00 00 00 00 Hello World.....
Hex Dump of wwHello.txt - note that output is wchar_t chars:
48 00 65 00 6c 00 6c 00 6f 00 20 00 57 00 6f 00 H.e.l.l.o. .W.o.
72 00 6c 00 64 00 00 00 00 00 00 00 00 00 00 00 r.l.d...........
КонструкторыConstructors
КонструкторConstructor | ОписаниеDescription |
---|---|
basic_filebufbasic_filebuf | Создает объект типа basic_filebuf .Constructs an object of type basic_filebuf . |
Определения типовTypedefs
Имя типаType name | ОписаниеDescription |
---|---|
char_typechar_type | Связывает имя типа с параметром шаблона Char_T .Associates a type name with the Char_T template parameter. |
int_typeint_type | Делает этот тип в области basic_filebuf эквивалентным типу с таким же именем в области Tr .Makes this type within basic_filebuf 's scope equivalent to the type of the same name in the Tr scope. |
off_typeoff_type | Делает этот тип в области basic_filebuf эквивалентным типу с таким же именем в области Tr .Makes this type within basic_filebuf 's scope equivalent to the type of the same name in the Tr scope. |
pos_typepos_type | Делает этот тип в области basic_filebuf эквивалентным типу с таким же именем в области Tr .Makes this type within basic_filebuf 's scope equivalent to the type of the same name in the Tr scope. |
traits_typetraits_type | Связывает имя типа с параметром шаблона Tr .Associates a type name with the Tr template parameter. |
Функции элементовMember functions
Функция-членMember function | ОписаниеDescription |
---|---|
closeclose | Закрывает файл.Closes a file. |
is_openis_open | Указывает, открыт ли файл.Indicates whether a file is open. |
openopen | Открывает файл.Opens a file. |
полнoverflow | Защищенная виртуальная функция, которая может вызываться при вставке нового символа в полный буфер.A protected virtual function that can be called when a new character is inserted into a full buffer. |
pbackfailpbackfail | Защищенная виртуальная функция-член пытается поместить элемент обратно во входной поток, затем делает его текущим (на него указывает следующий указатель).The protected virtual member function tries to put back an element into the input stream, then make it the current element (pointed to by the next pointer). |
seekoffseekoff | Защищенная виртуальная функция-член пытается изменить текущие положения управляемых потоков.The protected virtual member function tries to alter the current positions for the controlled streams. |
seekposseekpos | Защищенная виртуальная функция-член пытается изменить текущие положения управляемых потоков.The protected virtual member function tries to alter the current positions for the controlled streams. |
setbufsetbuf | Защищенная виртуальная функция-член выполняет операции, относящиеся непосредственно к каждому производному буферу потока.The protected virtual member function performs an operation particular to each derived stream buffer. |
ПозицииSwap | Меняет местами содержимое этого basic_filebuf и содержимое указанного параметра basic_filebuf .Exchanges the content of this basic_filebuf for the content of the provided basic_filebuf parameter. |
nosyncsync | Защищенная виртуальная функция пытается синхронизировать управляемые потоки с любыми связанными внешними потоками.Protected, virtual function tries to synchronize the controlled streams with any associated external streams. |
uflowuflow | Защищенная виртуальная функция для извлечения текущего элемента из входного потока.Protected, virtual function to extract the current element from the input stream. |
потери значимостиunderflow | Защищенная виртуальная функция для извлечения текущего элемента из входного потока.Protected, virtual function to extract the current element from the input stream. |
ТребованияRequirements
Заголовок:<fstream>Header: <fstream>
Пространство имен: stdNamespace: std
basic_filebuf:: basic_filebufbasic_filebuf::basic_filebuf
Создает объект типа basic_filebuf
.Constructs an object of type basic_filebuf
.
basic_filebuf();
basic_filebuf(basic_filebuf&& right);
КомментарииRemarks
Первый конструктор сохраняет пустой указатель во всех указателях, управляющих входным и выходным буферами.The first constructor stores a null pointer in all the pointers controlling the input buffer and the output buffer. Он также сохраняет пустой указатель в указателе файла.It also stores a null pointer in the file pointer.
Второй конструктор инициализирует объект с содержимым right, который рассматривается как ссылка rvalue.The second constructor initializes the object with the contents of right, treated as an rvalue reference.
basic_filebuf:: char_typebasic_filebuf::char_type
Связывает имя типа с параметром шаблона Char_T
.Associates a type name with the Char_T
template parameter.
typedef Char_T char_type;
basic_filebuf:: Closebasic_filebuf::close
Закрывает файл.Closes a file.
basic_filebuf<Char_T, Tr> *close();
Возвращаемое значениеReturn Value
Функция-член возвращает указатель null, если указатель файла является указателем null.The member function returns a null pointer if the file pointer is a null pointer.
КомментарииRemarks
close
вызывает fclose(fp)
.close
calls fclose(fp)
. Если эта функция возвращает ненулевое значение, то возвращается пустой указатель.If that function returns a nonzero value, the function returns a null pointer. В противном случае возвращается this
значение, указывающее, что файл был успешно закрыт.Otherwise, it returns this
to indicate that the file was successfully closed.
Для широкого потока, если с момента открытия потока или с момента последнего вызова в функцию возникли какие-либо операции вставки streampos
overflow
.For a wide stream, if any insertions have occurred since the stream was opened, or since the last call to streampos
, the function calls overflow
. Он также вставляет любую последовательность, необходимую для восстановления исходного состояния преобразования, с помощью аспекта преобразования файлов fac
для вызова fac.unshift
по мере необходимости.It also inserts any sequence needed to restore the initial conversion state, by using the file conversion facet fac
to call fac.unshift
as needed. Каждый созданный элемент byte
типа char
записывается в связанный поток, обозначенный указателем файла, как если бы они были fp
успешными вызовами формы fputc(byte, fp)
.Each produced element byte
of type char
is written to the associated stream designated by the file pointer fp
as if by successive calls of the form fputc(byte, fp)
. При fac.unshift
сбое вызова или любой записи функция не будет выполнена.If the call to fac.unshift
or any write fails, the function does not succeed.
ПримерExample
В следующем примере предполагается, что в текущем каталоге два файла: basic_filebuf_close.txt (содержимое — "тестирование") и iotest.txt (содержимое — "сссс").The following sample assumes two files in the current directory: basic_filebuf_close.txt (contents is "testing") and iotest.txt (contents is "ssss").
// basic_filebuf_close.cpp
// compile with: /EHsc
#include <fstream>
#include <iostream>
int main() {
using namespace std;
ifstream file;
basic_ifstream <wchar_t> wfile;
char c;
// Open and close with a basic_filebuf
file.rdbuf()->open( "basic_filebuf_close.txt", ios::in );
file >> c;
cout << c << endl;
file.rdbuf( )->close( );
// Open/close directly
file.open( "iotest.txt" );
file >> c;
cout << c << endl;
file.close( );
// open a file with a wide character name
wfile.open( L"iotest.txt" );
// Open and close a nonexistent with a basic_filebuf
file.rdbuf()->open( "ziotest.txt", ios::in );
cout << file.fail() << endl;
file.rdbuf( )->close( );
// Open/close directly
file.open( "ziotest.txt" );
cout << file.fail() << endl;
file.close( );
}
t
s
0
1
basic_filebuf:: int_typebasic_filebuf::int_type
Делает этот тип в basic_filebuf
области эквивалентным типу с тем же именем в Tr
области.Makes this type within basic_filebuf
scope equivalent to the type of the same name in the Tr
scope.
typedef typename traits_type::int_type int_type;
basic_filebuf:: is_openbasic_filebuf::is_open
Указывает, открыт ли файл.Indicates whether a file is open.
bool is_open() const;
Возвращаемое значениеReturn Value
true
значение, если указатель файла не равен null.true
if the file pointer isn't null.
ПримерExample
// basic_filebuf_is_open.cpp
// compile with: /EHsc
#include <fstream>
#include <iostream>
int main( )
{
using namespace std;
ifstream file;
cout << boolalpha << file.rdbuf( )->is_open( ) << endl;
file.open( "basic_filebuf_is_open.cpp" );
cout << file.rdbuf( )->is_open( ) << endl;
}
false
true
basic_filebuf:: off_typebasic_filebuf::off_type
Делает этот тип в basic_filebuf
области эквивалентным типу с тем же именем в Tr
области.Makes this type within basic_filebuf
scope equivalent to the type of the same name in the Tr
scope.
typedef typename traits_type::off_type off_type;
basic_filebuf:: Openbasic_filebuf::open
Открывает файл.Opens a file.
basic_filebuf<Char_T, Tr> *open(
const char* filename,
ios_base::openmode mode,
int protection = (int)ios_base::_Openprot);
basic_filebuf<Char_T, Tr> *open(
const char* filename,
ios_base::openmode mode);
basic_filebuf<Char_T, Tr> *open(
const wchar_t* filename,
ios_base::openmode mode,
int protection = (int)ios_base::_Openprot);
basic_filebuf<Char_T, Tr> *open(
const wchar_t* filename,
ios_base::openmode mode);
ПараметрыParameters
файловfilename
Имя файла, который необходимо открыть.The name of the file to open.
режимаmode
Одно из перечислений в ios_base::openmode
.One of the enumerations in ios_base::openmode
.
уровеньprotection
Защита открытия файлов по умолчанию, эквивалентная параметру шфлаг в _fsopen _wfsopen.The default file opening protection, equivalent to the shflag parameter in _fsopen, _wfsopen.
Возвращаемое значениеReturn Value
Если буфер уже открыт или если указатель файла является пустым указателем, функция возвращает пустой указатель.If the buffer is already open, or if the file pointer is a null pointer, the function returns a null pointer. В противном случае возвращается значение this
.Otherwise, it returns this
.
КомментарииRemarks
Эта функция использует FILE *
для возврата, basic_filebuf
как будто вы вызывали fopen/wfopen
(filename, strmode)
.This function uses a FILE *
to back the basic_filebuf
as though you had called fopen/wfopen
(filename, strmode)
. strmode
определяется из mode & ~(
ate
|
binary
)
:strmode
is determined from mode & ~(
ate
|
binary
)
:
ios_base::in
преобразуется"r"
(открывает существующий файл для чтения).ios_base::in
becomes"r"
(open existing file for reading).- ios_base:: out или
ios_base::out | ios_base::trunc
преобразуется"w"
(усечение существующего файла или создание для записи).ios_base::out orios_base::out | ios_base::trunc
becomes"w"
(truncate existing file or create for writing). ios_base::out | app
принимает"a"
(открывает существующий файл для добавления всех операций записи).ios_base::out | app
becomes"a"
(open existing file for appending all writes).ios_base::in | ios_base::out
преобразуется"r+"
(открывает существующий файл для чтения и записи).ios_base::in | ios_base::out
becomes"r+"
(open existing file for reading and writing).ios_base::in | ios_base::out | ios_base::trunc
преобразуется"w+"
(усекает существующий файл или создает для чтения и записи).ios_base::in | ios_base::out | ios_base::trunc
becomes"w+"
(truncate existing file or create for reading and writing).ios_base::in | ios_base::out | ios_base::app
принимает"a+"
(открывает существующий файл для чтения и для добавления всех операций записи).ios_base::in | ios_base::out | ios_base::app
becomes"a+"
(open existing file for reading and for appending all writes).
Если mode & ios_base::binary
имеет ненулевое значение, функция добавляет b
к, strmode
чтобы открыть двоичный поток вместо текстового потока.If mode & ios_base::binary
is nonzero, the function appends b
to strmode
to open a binary stream instead of a text stream.
Если mode & ios_base::ate
имеет ненулевое значение и файл был успешно открыт, текущее расположение в потоке размещается в конце файла.If mode & ios_base::ate
is nonzero and the file was succesfully opened, the current location in the stream is positioned at the end of file. Если это не удается, файл закрывается.If that fails, the file is closed.
Если приведенные выше операции завершились успешно, аспект преобразования файла определяется следующим образом: use_facet<codecvt<Char_T, char, traits_type::
state_type
> >(
getloc
)
, для использования в целях неточного и переполнения.If the above operations completed successfully, the file conversion facet is determined: use_facet<codecvt<Char_T, char, traits_type::
state_type
> >(
getloc
)
, for use by underflow and overflow.
Если файл не может быть успешно открыт, возвращается значение null.If the file could not be succesfully opened, null is returned.
ПримерExample
См basic_filebuf::close
. пример, в котором используется open
.See basic_filebuf::close
for an example that uses open
.
basic_filebuf:: operator =basic_filebuf::operator=
Назначьте содержимое этого объекта буфера потока.Assign the content of this stream buffer object. Это назначение перемещения, включающее rvalue, который не оставляет копию позади.This is a move assignment involving an rvalue that doesn't leave a copy behind.
basic_filebuf& operator=(basic_filebuf&& right);
ПараметрыParameters
Правильноright
Ссылка rvalue на объект basic_filebuf.An rvalue reference to a basic_filebuf object.
Возвращаемое значениеReturn Value
Возвращает * this.Returns *this.
КомментарииRemarks
Оператор Member заменяет содержимое объекта с помощью содержимого right, которое рассматривается как ссылка rvalue.The member operator replaces the contents of the object by using the contents of right, treated as an rvalue reference. Дополнительные сведения см. в разделе декларатор ссылок rvalue: &&.For more information, see Rvalue reference declarator: &&.
basic_filebuf:: overflowbasic_filebuf::overflow
Вызывается при вставке нового символа в полный буфер.Called when a new character is inserted into a full buffer.
virtual int_type overflow(int_type _Meta = traits_type::eof);
ПараметрыParameters
_Meta_Meta
Символ, вставляемый в буфер или traits_type::eof
.The character to insert into the buffer or traits_type::eof
.
Возвращаемое значениеReturn Value
Если функция не может быть выполнена, возвращается значение traits_type::eof
.If the function can't succeed, it returns traits_type::eof
. В противном случае возвращается значение traits_type::
not_eof
(_Meta)
.Otherwise, it returns traits_type::
not_eof
(_Meta)
.
КомментарииRemarks
Если _Meta != traits_type::
eof
значение равно, Защищенная виртуальная функция – член пытается вставить элемент ch = traits_type::
to_char_type
(_Meta)
в выходной буфер.If _Meta != traits_type::
eof
, the protected virtual member function attempts to insert the element ch = traits_type::
to_char_type
(_Meta)
into the output buffer. Это можно сделать разными способами.It can do so in various ways:
Если позиция записи доступна, можно сохранить элемент в позиции записи и увеличить следующий указатель для выходного буфера.If a write position is available, it can store the element into the write position and increment the next pointer for the output buffer.
Можно сделать позицию записи доступной, выделяя новое или дополнительное хранилище для выходного буфера.It can make a write position available by allocating new or additional storage for the output buffer.
Он может преобразовать все ожидающие выходные данные в выходной буфер, за которым следует
ch
, с помощью аспекта преобразования файловfac
для вызоваfac.out
по мере необходимости.It can convert any pending output in the output buffer, followed bych
, by using the file conversion facetfac
to callfac.out
as needed. Каждый созданный элементch
типа char записывается в связанный поток, обозначенный указателем файла, как если бы они былиfp
успешными вызовами формыfputc(ch, fp)
.Each produced elementch
of type char is written to the associated stream designated by the file pointerfp
as if by successive calls of the formfputc(ch, fp)
. В случае сбоя любого преобразования или записи эта функция завершается неудачно.If any conversion or write fails, the function does not succeed.
basic_filebuf: неудачная:pbasic_filebuf::pbackfail
Пытается поместить элемент обратно во входной поток, затем делает его текущим (на него указывает следующий указатель).Tries to put back an element into the input stream, then make it the current element (pointed to by the next pointer).
virtual int_type pbackfail(int_type _Meta = traits_type::eof);
ПараметрыParameters
_Meta_Meta
Символ для вставки в буфер или traits_type::eof
.The character to insert into the buffer, or traits_type::eof
.
Возвращаемое значениеReturn Value
Если функция не может быть выполнена, возвращается значение traits_type::eof
.If the function can't succeed, it returns traits_type::eof
. В противном случае возвращается значение traits_type::
not_eof
(_Meta)
.Otherwise, it returns traits_type::
not_eof
(_Meta)
.
КомментарииRemarks
Защищенная виртуальная функция-член помещает элемент обратно во входной буфер, а затем делает его текущим (на него указывает следующий указатель).The protected virtual member function puts back an element into the input buffer and then makes it the current element (pointed to by the next pointer). Если _Meta == traits_type::
eof
значение равно, то элемент, который необходимо вернуть обратно, фактически является уже в потоке до текущего элемента.If _Meta == traits_type::
eof
, the element to push back is effectively the one already in the stream before the current element. В противном случае этот элемент заменяется на ch = traits_type::
to_char_type
(_Meta)
.Otherwise, that element is replaced by ch = traits_type::
to_char_type
(_Meta)
. Функция может передать элемент обратно различными способами.The function can put back an element in various ways:
Если
putback
расположение доступно, а элемент, в котором хранится, сравнивается со значениемch
, он может уменьшить следующий указатель для входного буфера.If aputback
position is available, and the element stored there compares equal toch
, it can decrement the next pointer for the input buffer.Если функция может сделать
putback
позицию доступной, она может сделать это, установить следующий указатель, указывающий на эту позицию, и сохранитьch
его в этой позиции.If the function can make aputback
position available, it can do so, set the next pointer to point at that position, and storech
in that position.Если функция может вернуть элемент во входной поток, это может сделать это, например, путем вызова
ungetc
для элемента типаchar
.If the function can push back an element onto the input stream, it can do so, such as by callingungetc
for an element of typechar
.
basic_filebuf::p os_typebasic_filebuf::pos_type
Делает этот тип в basic_filebuf
области эквивалентным типу с тем же именем в Tr
области.Makes this type within basic_filebuf
scope equivalent to the type of the same name in the Tr
scope.
typedef typename traits_type::pos_type pos_type;
basic_filebuf:: seekoffbasic_filebuf::seekoff
Пытается изменить текущие положения для управляемых потоков.Tries to alter the current positions for the controlled streams.
virtual pos_type seekoff(
off_type _Off,
ios_base::seekdir _Way,
ios_base::openmode _Which = ios_base::in | ios_base::out);
ПараметрыParameters
_Off_Off
Искомое положение относительно _Way.The position to seek for relative to _Way.
_Way_Way
Начальная точка для операций смещения.The starting point for offset operations. Возможные значения см. в разделе seekdir.See seekdir for possible values.
_Which_Which
Задает режим для положения указателя.Specifies the mode for the pointer position. По умолчанию разрешается изменять позиции чтения и записи.The default is to allow you to modify the read and write positions.
Возвращаемое значениеReturn Value
Возвращает новую позицию или недопустимую позицию потока.Returns the new position or an invalid stream position.
КомментарииRemarks
Защищенная виртуальная функция – член пытается изменить текущие позиции для управляемых потоков.The protected virtual member function attempts to alter the current positions for the controlled streams. Для объекта класса basic_filebuf
<Char_T, Tr>
позиция потока может быть представлена объектом типа fpos_t
, который хранит смещение и все сведения о состоянии, необходимые для синтаксического анализа большого потока.For an object of class basic_filebuf
<Char_T, Tr>
, a stream position can be represented by an object of type fpos_t
, which stores an offset and any state information needed to parse a wide stream. Нулевое смещение относится к первому элементу потока.Offset zero refers to the first element of the stream. (Объект типа pos_type
хранит по крайней мере fpos_t
объект.)(An object of type pos_type
stores at least an fpos_t
object.)
Для файла, открытого для чтения и записи, входной и выходной потоки располагаются вместе.For a file opened for both reading and writing, both the input and output streams are positioned in tandem. Для переключения между вставкой и извлечением необходимо вызвать либо pubseekoff
pubseekpos
.To switch between inserting and extracting, you must call either pubseekoff
or pubseekpos
. Вызовы pubseekoff
(и, следовательно, seekoff
) имеют различные ограничения для текстовых потоков, двоичных потокови широких потоков.Calls to pubseekoff
(and hence to seekoff
) have various limitations for text streams, binary streams, and wide streams.
Если указатель файла fp
является пустым указателем, функция завершается ошибкой.If the file pointer fp
is a null pointer, the function fails. В противном случае он пытается изменить расположение потока путем вызова fseek(fp, _Off, _Way)
.Otherwise, it attempts to alter the stream position by calling fseek(fp, _Off, _Way)
. Если эта функция завершилась с ошибкой и результирующая положение fposn
может быть определено вызовом fgetpos(fp, &fposn)
функции, функция будет выполнена.If that function succeeds and the resulting position fposn
can be determined by calling fgetpos(fp, &fposn)
, the function succeeds. Если функция завершается с ошибкой, она возвращает значение типа, pos_type
содержащее fposn
.If the function succeeds, it returns a value of type pos_type
containing fposn
. В противном случае она возвращает недопустимую позицию потока.Otherwise, it returns an invalid stream position.
basic_filebuf:: seekposbasic_filebuf::seekpos
Пытается изменить текущие положения для управляемых потоков.Tries to alter the current positions for the controlled streams.
virtual pos_type seekpos(
pos_type _Sp,
ios_base::openmode _Which = ios_base::in | ios_base::out);
ПараметрыParameters
_Sp_Sp
Позиция для поиска.The position to seek for.
_Which_Which
Задает режим для положения указателя.Specifies the mode for the pointer position. По умолчанию разрешается изменять позиции чтения и записи.The default is to allow you to modify the read and write positions.
Возвращаемое значениеReturn Value
Если указатель файла fp
является пустым указателем, функция завершается ошибкой.If the file pointer fp
is a null pointer, the function fails. В противном случае он пытается изменить позицию потока путем вызова метода fsetpos(fp, &fposn)
, где fposn
— это fpos_t
объект, хранящийся в pos
.Otherwise, it attempts to alter the stream position by calling fsetpos(fp, &fposn)
, where fposn
is the fpos_t
object stored in pos
. Если эта функция выполняется успешно, функция возвращает pos
.If that function succeeds, the function returns pos
. В противном случае она возвращает недопустимую позицию потока.Otherwise, it returns an invalid stream position. Чтобы определить, является ли позиция в потоке недопустимой, сравните возвращаемое значение с pos_type(off_type(-1))
.To determine if the stream position is invalid, compare the return value with pos_type(off_type(-1))
.
КомментарииRemarks
Защищенная виртуальная функция – член пытается изменить текущие позиции для управляемых потоков.The protected virtual member function attempts to alter the current positions for the controlled streams. Для объекта класса basic_filebuf
<Char_T, Tr>
позиция потока может быть представлена объектом типа fpos_t
, который хранит смещение и все сведения о состоянии, необходимые для синтаксического анализа большого потока.For an object of class basic_filebuf
<Char_T, Tr>
, a stream position can be represented by an object of type fpos_t
, which stores an offset and any state information needed to parse a wide stream. Нулевое смещение относится к первому элементу потока.Offset zero refers to the first element of the stream. (Объект типа pos_type
хранит по крайней мере объект fpos_t
.)(An object of type pos_type
stores at least an fpos_t
object.)
Для файла, открытого для чтения и записи, входной и выходной потоки располагаются вместе.For a file opened for both reading and writing, both the input and output streams are positioned in tandem. Для переключения между вставкой и извлечением необходимо вызвать либо pubseekoff
pubseekpos
.To switch between inserting and extracting, you must call either pubseekoff
or pubseekpos
. Вызовы pubseekoff
(и в seekoff
) имеют различные ограничения для текстовых потоков, двоичных потоков и широких потоков.Calls to pubseekoff
(and to seekoff
) have various limitations for text streams, binary streams, and wide streams.
Что касается широкого потока, если после открытия такого потока или с момента последнего вызова streampos
были произведены какие-либо вставки, то эта функция вызывает переполнение.For a wide stream, if any insertions have occurred since the stream was opened, or since the last call to streampos
, the function calls overflow. Он также вставляет любую последовательность, необходимую для восстановления исходного состояния преобразования, с помощью аспекта преобразования файлов fac
для вызова fac.unshift
по мере необходимости.It also inserts any sequence needed to restore the initial conversion state, by using the file conversion facet fac
to call fac.unshift
as needed. Каждый созданный элемент byte
типа char
записывается в связанный поток, обозначенный указателем файла, как если бы они были fp
успешными вызовами формы fputc(byte, fp)
.Each produced element byte
of type char
is written to the associated stream designated by the file pointer fp
as if by successive calls of the form fputc(byte, fp)
. При fac.unshift
сбое вызова или любой записи функция не будет выполнена.If the call to fac.unshift
or any write fails, the function does not succeed.
basic_filebuf:: setbufbasic_filebuf::setbuf
Выполняет операции, относящиеся непосредственно к каждому производному буферу потока.Performs an operation particular to each derived stream buffer.
virtual basic_streambuf<Char_T, Tr> *setbuf(
char_type* _Buffer,
streamsize count);
ПараметрыParameters
_Buffer_Buffer
Указатель на буфер.Pointer to a buffer.
расчетаcount
Размер буфера.Size of the buffer.
Возвращаемое значениеReturn Value
Эта защищенная функция-член возвращает нуль, если указатель файла fp
является пустым указателем.The protected member function returns zero if the file pointer fp
is a null pointer.
КомментарииRemarks
setbuf
вызывает метод setvbuf( fp, (char*) _Buffer, _IOFBF, count * sizeof( Char_T))
для предложения массива count
элементов, начиная с _Buffer в виде буфера для потока.setbuf
calls setvbuf( fp, (char*) _Buffer, _IOFBF, count * sizeof( Char_T))
to offer the array of count
elements beginning at _Buffer as a buffer for the stream. Если эта функция возвращает ненулевое значение, то возвращается пустой указатель.If that function returns a nonzero value, the function returns a null pointer. В противном случае возвращается this
значение для успешного сигнала.Otherwise, it returns this
to signal success.
basic_filebuf:: swapbasic_filebuf::swap
Меняет местами содержимое этого объекта basic_filebuf
с содержимым указанного объекта basic_filebuf
.Exchanges the contents of this basic_filebuf
for the contents of the provided basic_filebuf
.
void swap(basic_filebuf& right);
ПараметрыParameters
Правильноright
Ссылка lvalue на другую basic_filebuf
.An lvalue reference to another basic_filebuf
.
basic_filebuf:: Syncbasic_filebuf::sync
Пытается синхронизировать управляемые потоки с любыми связанными внешними потоками.Tries to synchronize the controlled streams with any associated external streams.
virtual int sync();
Возвращаемое значениеReturn Value
Возвращает нуль, если указатель файла fp
является пустым указателем.Returns zero if the file pointer fp
is a null pointer. В противном случае он возвращает нуль только в том случае, если вызовы обоих типов вызывают переполнение и fflush(fp)
выполняются при сбросе всех ожидающих выходных данных в поток.Otherwise, it returns zero only if calls to both overflow and fflush(fp)
succeed in flushing any pending output to the stream.
basic_filebuf:: traits_typebasic_filebuf::traits_type
Связывает имя типа с параметром шаблона Tr
.Associates a type name with the Tr
template parameter.
typedef Tr traits_type;
basic_filebuf:: потеря значимостиbasic_filebuf::underflow
Извлекает текущий элемент из входного потока.Extracts the current element from the input stream.
virtual int_type underflow();
Возвращаемое значениеReturn Value
Если функция не может быть выполнена, возвращается значение traits_type::
eof
.If the function can't succeed, it returns traits_type::
eof
. В противном случае возвращается ch
, преобразуется, как описано в разделе "Примечания".Otherwise, it returns ch
, converted as described in the Remarks section.
КомментарииRemarks
Защищенная виртуальная функция члена пытается извлечь текущий элемент ch
из входного потока и вернуть элемент в качестве traits_type::
to_int_type
(ch)
.The protected virtual member function attempts to extract the current element ch
from the input stream, and return the element as traits_type::
to_int_type
(ch)
. Это можно сделать разными способами.It can do so in various ways:
Если доступная для чтения позиции доступна, она принимает в
ch
качестве элемента, хранящегося в позиции чтения, и перемещает следующий указатель для входного буфера.If a read position is available, it takesch
as the element stored in the read position and advances the next pointer for the input buffer.Он может считывать один или несколько элементов типа
char
, как при последовательных вызовах формыfgetc(fp)
, так и преобразовывать их в элементch
типаChar_T
, используя аспект преобразования файлаfac
для вызоваfac.in
по мере необходимости.It can read one or more elements of typechar
, as if by successive calls of the formfgetc(fp)
, and convert them to an elementch
of typeChar_T
by using the file conversion facetfac
to callfac.in
as needed. В случае сбоя какого-либо преобразования или операции чтения эта функция завершается неудачно.If any read or conversion fails, the function does not succeed.
См. также разделSee also
<fstream>
Безопасность потоков в стандартной библиотеке C++Thread Safety in the C++ Standard Library
Программирование iostreamiostream Programming
Соглашения iostreamiostreams Conventions