如果这篇博客帮助到你,可以请我喝一杯咖啡~
CC BY 4.0 (除特别声明或转载文章外)
ios_base
#ifndef _IOS_BASE_H
#define _IOS_BASE_H 1
#pragma GCC system_header
#include <ext/atomicity.h>
#include <bits/localefwd.h>
#include <bits/locale_classes.h>
# include <system_error>
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
// The following definitions of bitmask types are enums, not ints,
// as permitted (but not required) in the standard, in order to provide
// better type safety in iostream calls. A side effect is that in C++98
// expressions involving them are not compile-time constants.
enum _Ios_Fmtflags
{
_S_boolalpha = 1L << 0,
_S_dec = 1L << 1,
_S_fixed = 1L << 2,
_S_hex = 1L << 3,
_S_internal = 1L << 4,
_S_left = 1L << 5,
_S_oct = 1L << 6,
_S_right = 1L << 7,
_S_scientific = 1L << 8,
_S_showbase = 1L << 9,
_S_showpoint = 1L << 10,
_S_showpos = 1L << 11,
_S_skipws = 1L << 12,
_S_unitbuf = 1L << 13,
_S_uppercase = 1L << 14,
_S_adjustfield = _S_left | _S_right | _S_internal,
_S_basefield = _S_dec | _S_oct | _S_hex,
_S_floatfield = _S_scientific | _S_fixed,
_S_ios_fmtflags_end = 1L << 16,
_S_ios_fmtflags_max = __INT_MAX__,
_S_ios_fmtflags_min = ~__INT_MAX__
};
inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags
operator&(_Ios_Fmtflags __a, _Ios_Fmtflags __b)
{ return _Ios_Fmtflags(static_cast<int>(__a) & static_cast<int>(__b)); }
inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags
operator|(_Ios_Fmtflags __a, _Ios_Fmtflags __b)
{ return _Ios_Fmtflags(static_cast<int>(__a) | static_cast<int>(__b)); }
inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags
operator^(_Ios_Fmtflags __a, _Ios_Fmtflags __b)
{ return _Ios_Fmtflags(static_cast<int>(__a) ^ static_cast<int>(__b)); }
inline _GLIBCXX_CONSTEXPR _Ios_Fmtflags
operator~(_Ios_Fmtflags __a)
{ return _Ios_Fmtflags(~static_cast<int>(__a)); }
inline const _Ios_Fmtflags&
operator|=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b)
{ return __a = __a | __b; }
inline const _Ios_Fmtflags&
operator&=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b)
{ return __a = __a & __b; }
inline const _Ios_Fmtflags&
operator^=(_Ios_Fmtflags& __a, _Ios_Fmtflags __b)
{ return __a = __a ^ __b; }
enum _Ios_Openmode
{
_S_app = 1L << 0,
_S_ate = 1L << 1,
_S_bin = 1L << 2,
_S_in = 1L << 3,
_S_out = 1L << 4,
_S_trunc = 1L << 5,
_S_ios_openmode_end = 1L << 16,
_S_ios_openmode_max = __INT_MAX__,
_S_ios_openmode_min = ~__INT_MAX__
};
inline _GLIBCXX_CONSTEXPR _Ios_Openmode
operator&(_Ios_Openmode __a, _Ios_Openmode __b)
{ return _Ios_Openmode(static_cast<int>(__a) & static_cast<int>(__b)); }
inline _GLIBCXX_CONSTEXPR _Ios_Openmode
operator|(_Ios_Openmode __a, _Ios_Openmode __b)
{ return _Ios_Openmode(static_cast<int>(__a) | static_cast<int>(__b)); }
inline _GLIBCXX_CONSTEXPR _Ios_Openmode
operator^(_Ios_Openmode __a, _Ios_Openmode __b)
{ return _Ios_Openmode(static_cast<int>(__a) ^ static_cast<int>(__b)); }
inline _GLIBCXX_CONSTEXPR _Ios_Openmode
operator~(_Ios_Openmode __a)
{ return _Ios_Openmode(~static_cast<int>(__a)); }
inline const _Ios_Openmode&
operator|=(_Ios_Openmode& __a, _Ios_Openmode __b)
{ return __a = __a | __b; }
inline const _Ios_Openmode&
operator&=(_Ios_Openmode& __a, _Ios_Openmode __b)
{ return __a = __a & __b; }
inline const _Ios_Openmode&
operator^=(_Ios_Openmode& __a, _Ios_Openmode __b)
{ return __a = __a ^ __b; }
enum _Ios_Iostate
{
_S_goodbit = 0,
_S_badbit = 1L << 0,
_S_eofbit = 1L << 1,
_S_failbit = 1L << 2,
_S_ios_iostate_end = 1L << 16,
_S_ios_iostate_max = __INT_MAX__,
_S_ios_iostate_min = ~__INT_MAX__
};
inline _GLIBCXX_CONSTEXPR _Ios_Iostate
operator&(_Ios_Iostate __a, _Ios_Iostate __b)
{ return _Ios_Iostate(static_cast<int>(__a) & static_cast<int>(__b)); }
inline _GLIBCXX_CONSTEXPR _Ios_Iostate
operator|(_Ios_Iostate __a, _Ios_Iostate __b)
{ return _Ios_Iostate(static_cast<int>(__a) | static_cast<int>(__b)); }
inline _GLIBCXX_CONSTEXPR _Ios_Iostate
operator^(_Ios_Iostate __a, _Ios_Iostate __b)
{ return _Ios_Iostate(static_cast<int>(__a) ^ static_cast<int>(__b)); }
inline _GLIBCXX_CONSTEXPR _Ios_Iostate
operator~(_Ios_Iostate __a)
{ return _Ios_Iostate(~static_cast<int>(__a)); }
inline const _Ios_Iostate&
operator|=(_Ios_Iostate& __a, _Ios_Iostate __b)
{ return __a = __a | __b; }
inline const _Ios_Iostate&
operator&=(_Ios_Iostate& __a, _Ios_Iostate __b)
{ return __a = __a & __b; }
inline const _Ios_Iostate&
operator^=(_Ios_Iostate& __a, _Ios_Iostate __b)
{ return __a = __a ^ __b; }
enum _Ios_Seekdir
{
_S_beg = 0,
_S_cur = _GLIBCXX_STDIO_SEEK_CUR,
_S_end = _GLIBCXX_STDIO_SEEK_END,
_S_ios_seekdir_end = 1L << 16
};
// 27.4.2 Class ios_base
/**
* @brief The base of the I/O class hierarchy.
* @ingroup io
*
* This class defines everything that can be defined about I/O that does
* not depend on the type of characters being input or output. Most
* people will only see @c ios_base when they need to specify the full
* name of the various I/O flags (e.g., the openmodes).
*/
class ios_base
{
public:
/**
* @brief These are thrown to indicate problems with io.
* @ingroup exceptions
*
* 27.4.2.1.1 Class ios_base::failure
*/
// 27.4.2.1.2 Type ios_base::fmtflags
/**
* @brief This is a bitmask type.
*
* @c @a _Ios_Fmtflags is implementation-defined, but it is valid to
* perform bitwise operations on these values and expect the Right
* Thing to happen. Defined objects of type fmtflags are:
* - boolalpha
* - dec
* - fixed
* - hex
* - internal
* - left
* - oct
* - right
* - scientific
* - showbase
* - showpoint
* - showpos
* - skipws
* - unitbuf
* - uppercase
* - adjustfield
* - basefield
* - floatfield
*/
typedef _Ios_Fmtflags fmtflags;
/// Insert/extract @c bool in alphabetic rather than numeric format.
static const fmtflags boolalpha = _S_boolalpha;
/// Converts integer input or generates integer output in decimal base.
static const fmtflags dec = _S_dec;
/// Generate floating-point output in fixed-point notation.
static const fmtflags fixed = _S_fixed;
/// Converts integer input or generates integer output in hexadecimal base.
static const fmtflags hex = _S_hex;
/// Adds fill characters at a designated internal point in certain
/// generated output, or identical to @c right if no such point is
/// designated.
static const fmtflags internal = _S_internal;
/// Adds fill characters on the right (final positions) of certain
/// generated output. (I.e., the thing you print is flush left.)
static const fmtflags left = _S_left;
/// Converts integer input or generates integer output in octal base.
static const fmtflags oct = _S_oct;
/// Adds fill characters on the left (initial positions) of certain
/// generated output. (I.e., the thing you print is flush right.)
static const fmtflags right = _S_right;
/// Generates floating-point output in scientific notation.
static const fmtflags scientific = _S_scientific;
/// Generates a prefix indicating the numeric base of generated integer
/// output.
static const fmtflags showbase = _S_showbase;
/// Generates a decimal-point character unconditionally in generated
/// floating-point output.
static const fmtflags showpoint = _S_showpoint;
/// Generates a + sign in non-negative generated numeric output.
static const fmtflags showpos = _S_showpos;
/// Skips leading white space before certain input operations.
static const fmtflags skipws = _S_skipws;
/// Flushes output after each output operation.
static const fmtflags unitbuf = _S_unitbuf;
/// Replaces certain lowercase letters with their uppercase equivalents
/// in generated output.
static const fmtflags uppercase = _S_uppercase;
/// A mask of left|right|internal. Useful for the 2-arg form of @c setf.
static const fmtflags adjustfield = _S_adjustfield;
/// A mask of dec|oct|hex. Useful for the 2-arg form of @c setf.
static const fmtflags basefield = _S_basefield;
/// A mask of scientific|fixed. Useful for the 2-arg form of @c setf.
static const fmtflags floatfield = _S_floatfield;
// 27.4.2.1.3 Type ios_base::iostate
/**
* @brief This is a bitmask type.
*
* @c @a _Ios_Iostate is implementation-defined, but it is valid to
* perform bitwise operations on these values and expect the Right
* Thing to happen. Defined objects of type iostate are:
* - badbit
* - eofbit
* - failbit
* - goodbit
*/
typedef _Ios_Iostate iostate;
/// Indicates a loss of integrity in an input or output sequence (such
/// as an irrecoverable read error from a file).
static const iostate badbit = _S_badbit;
/// Indicates that an input operation reached the end of an input sequence.
static const iostate eofbit = _S_eofbit;
/// Indicates that an input operation failed to read the expected
/// characters, or that an output operation failed to generate the
/// desired characters.
static const iostate failbit = _S_failbit;
/// Indicates all is well.
static const iostate goodbit = _S_goodbit;
// 27.4.2.1.4 Type ios_base::openmode
/**
* @brief This is a bitmask type.
*
* @c @a _Ios_Openmode is implementation-defined, but it is valid to
* perform bitwise operations on these values and expect the Right
* Thing to happen. Defined objects of type openmode are:
* - app
* - ate
* - binary
* - in
* - out
* - trunc
*/
typedef _Ios_Openmode openmode;
/// Seek to end before each write.
static const openmode app = _S_app;
/// Open and seek to end immediately after opening.
static const openmode ate = _S_ate;
/// Perform input and output in binary mode (as opposed to text mode).
/// This is probably not what you think it is; see
/// https://gcc.gnu.org/onlinedocs/libstdc++/manual/fstreams.html#std.io.filestreams.binary
static const openmode binary = _S_bin;
/// Open for input. Default for @c ifstream and fstream.
static const openmode in = _S_in;
/// Open for output. Default for @c ofstream and fstream.
static const openmode out = _S_out;
/// Open for input. Default for @c ofstream.
static const openmode trunc = _S_trunc;
// 27.4.2.1.5 Type ios_base::seekdir
/**
* @brief This is an enumerated type.
*
* @c @a _Ios_Seekdir is implementation-defined. Defined values
* of type seekdir are:
* - beg
* - cur, equivalent to @c SEEK_CUR in the C standard library.
* - end, equivalent to @c SEEK_END in the C standard library.
*/
typedef _Ios_Seekdir seekdir;
/// Request a seek relative to the beginning of the stream.
static const seekdir beg = _S_beg;
/// Request a seek relative to the current position within the sequence.
static const seekdir cur = _S_cur;
/// Request a seek relative to the current end of the sequence.
static const seekdir end = _S_end;
typedef int io_state;
typedef int open_mode;
typedef int seek_dir;
typedef std::streampos streampos;
typedef std::streamoff streamoff;
// Callbacks;
/**
* @brief The set of events that may be passed to an event callback.
*
* erase_event is used during ~ios() and copyfmt(). imbue_event is used
* during imbue(). copyfmt_event is used during copyfmt().
*/
enum event
{
erase_event,
imbue_event,
copyfmt_event
};
/**
* @brief The type of an event callback function.
* @param __e One of the members of the event enum.
* @param __b Reference to the ios_base object.
* @param __i The integer provided when the callback was registered.
*
* Event callbacks are user defined functions that get called during
* several ios_base and basic_ios functions, specifically imbue(),
* copyfmt(), and ~ios().
*/
typedef void (*event_callback) (event __e, ios_base& __b, int __i);
/**
* @brief Add the callback __fn with parameter __index.
* @param __fn The function to add.
* @param __index The integer to pass to the function when invoked.
*
* Registers a function as an event callback with an integer parameter to
* be passed to the function when invoked. Multiple copies of the
* function are allowed. If there are multiple callbacks, they are
* invoked in the order they were registered.
*/
void
register_callback(event_callback __fn, int __index);
protected:
streamsize _M_precision;
streamsize _M_width;
fmtflags _M_flags;
iostate _M_exception;
iostate _M_streambuf_state;
public:
// [27.4.2.2] fmtflags state functions
/**
* @brief Access to format flags.
* @return The format control flags for both input and output.
*/
fmtflags
flags() const
{ return _M_flags; }
/**
* @brief Setting new format flags all at once.
* @param __fmtfl The new flags to set.
* @return The previous format control flags.
*
* This function overwrites all the format flags with @a __fmtfl.
*/
fmtflags
flags(fmtflags __fmtfl)
{
fmtflags __old = _M_flags;
_M_flags = __fmtfl;
return __old;
}
/**
* @brief Setting new format flags.
* @param __fmtfl Additional flags to set.
* @return The previous format control flags.
*
* This function sets additional flags in format control. Flags that
* were previously set remain set.
*/
fmtflags
setf(fmtflags __fmtfl)
{
fmtflags __old = _M_flags;
_M_flags |= __fmtfl;
return __old;
}
/**
* @brief Setting new format flags.
* @param __fmtfl Additional flags to set.
* @param __mask The flags mask for @a fmtfl.
* @return The previous format control flags.
*
* This function clears @a mask in the format flags, then sets
* @a fmtfl @c & @a mask. An example mask is @c ios_base::adjustfield.
*/
fmtflags
setf(fmtflags __fmtfl, fmtflags __mask)
{
fmtflags __old = _M_flags;
_M_flags &= ~__mask;
_M_flags |= (__fmtfl & __mask);
return __old;
}
/**
* @brief Clearing format flags.
* @param __mask The flags to unset.
*
* This function clears @a __mask in the format flags.
*/
void
unsetf(fmtflags __mask)
{ _M_flags &= ~__mask; }
/**
* @brief Flags access.
* @return The precision to generate on certain output operations.
*
* Be careful if you try to give a definition of @a precision here; see
* DR 189.
*/
streamsize
precision() const
{ return _M_precision; }
/**
* @brief Changing flags.
* @param __prec The new precision value.
* @return The previous value of precision().
*/
streamsize
precision(streamsize __prec)
{
streamsize __old = _M_precision;
_M_precision = __prec;
return __old;
}
/**
* @brief Flags access.
* @return The minimum field width to generate on output operations.
*
* <em>Minimum field width</em> refers to the number of characters.
*/
streamsize
width() const
{ return _M_width; }
/**
* @brief Changing flags.
* @param __wide The new width value.
* @return The previous value of width().
*/
streamsize
width(streamsize __wide)
{
streamsize __old = _M_width;
_M_width = __wide;
return __old;
}
// [27.4.2.4] ios_base static members
/**
* @brief Interaction with the standard C I/O objects.
* @param __sync Whether to synchronize or not.
* @return True if the standard streams were previously synchronized.
*
* The synchronization referred to is @e only that between the standard
* C facilities (e.g., stdout) and the standard C++ objects (e.g.,
* cout). User-declared streams are unaffected. See
* https://gcc.gnu.org/onlinedocs/libstdc++/manual/fstreams.html#std.io.filestreams.binary
*/
static bool
sync_with_stdio(bool __sync = true);
// [27.4.2.3] ios_base locale functions
/**
* @brief Setting a new locale.
* @param __loc The new locale.
* @return The previous locale.
*
* Sets the new locale for this stream, and then invokes each callback
* with imbue_event.
*/
// Destructor
/**
* Invokes each callback with erase_event. Destroys local storage.
*
* Note that the ios_base object for the standard streams never gets
* destroyed. As a result, any callbacks registered with the standard
* streams will not get invoked with erase_event (unless copyfmt is
* used).
*/
virtual ~ios_base();
protected:
ios_base() throw ();
#if __cplusplus < 201103L
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// 50. Copy constructor and assignment operator of ios_base
private:
ios_base(const ios_base&);
ios_base&
operator=(const ios_base&);
#else
public:
ios_base(const ios_base&) = delete;
ios_base&
operator=(const ios_base&) = delete;
protected:
void
_M_move(ios_base&) noexcept;
void
_M_swap(ios_base& __rhs) noexcept;
#endif
};
// [27.4.5.1] fmtflags manipulators
/// Calls base.setf(ios_base::boolalpha).
inline ios_base&
boolalpha(ios_base& __base)
{
__base.setf(ios_base::boolalpha);
return __base;
}
/// Calls base.unsetf(ios_base::boolalpha).
inline ios_base&
noboolalpha(ios_base& __base)
{
__base.unsetf(ios_base::boolalpha);
return __base;
}
/// Calls base.setf(ios_base::showbase).
inline ios_base&
showbase(ios_base& __base)
{
__base.setf(ios_base::showbase);
return __base;
}
/// Calls base.unsetf(ios_base::showbase).
inline ios_base&
noshowbase(ios_base& __base)
{
__base.unsetf(ios_base::showbase);
return __base;
}
/// Calls base.setf(ios_base::showpoint).
inline ios_base&
showpoint(ios_base& __base)
{
__base.setf(ios_base::showpoint);
return __base;
}
/// Calls base.unsetf(ios_base::showpoint).
inline ios_base&
noshowpoint(ios_base& __base)
{
__base.unsetf(ios_base::showpoint);
return __base;
}
/// Calls base.setf(ios_base::showpos).
inline ios_base&
showpos(ios_base& __base)
{
__base.setf(ios_base::showpos);
return __base;
}
/// Calls base.unsetf(ios_base::showpos).
inline ios_base&
noshowpos(ios_base& __base)
{
__base.unsetf(ios_base::showpos);
return __base;
}
/// Calls base.setf(ios_base::skipws).
inline ios_base&
skipws(ios_base& __base)
{
__base.setf(ios_base::skipws);
return __base;
}
/// Calls base.unsetf(ios_base::skipws).
inline ios_base&
noskipws(ios_base& __base)
{
__base.unsetf(ios_base::skipws);
return __base;
}
/// Calls base.setf(ios_base::uppercase).
inline ios_base&
uppercase(ios_base& __base)
{
__base.setf(ios_base::uppercase);
return __base;
}
/// Calls base.unsetf(ios_base::uppercase).
inline ios_base&
nouppercase(ios_base& __base)
{
__base.unsetf(ios_base::uppercase);
return __base;
}
/// Calls base.setf(ios_base::unitbuf).
inline ios_base&
unitbuf(ios_base& __base)
{
__base.setf(ios_base::unitbuf);
return __base;
}
/// Calls base.unsetf(ios_base::unitbuf).
inline ios_base&
nounitbuf(ios_base& __base)
{
__base.unsetf(ios_base::unitbuf);
return __base;
}
// [27.4.5.2] adjustfield manipulators
/// Calls base.setf(ios_base::internal, ios_base::adjustfield).
inline ios_base&
internal(ios_base& __base)
{
__base.setf(ios_base::internal, ios_base::adjustfield);
return __base;
}
/// Calls base.setf(ios_base::left, ios_base::adjustfield).
inline ios_base&
left(ios_base& __base)
{
__base.setf(ios_base::left, ios_base::adjustfield);
return __base;
}
/// Calls base.setf(ios_base::right, ios_base::adjustfield).
inline ios_base&
right(ios_base& __base)
{
__base.setf(ios_base::right, ios_base::adjustfield);
return __base;
}
// [27.4.5.3] basefield manipulators
/// Calls base.setf(ios_base::dec, ios_base::basefield).
inline ios_base&
dec(ios_base& __base)
{
__base.setf(ios_base::dec, ios_base::basefield);
return __base;
}
/// Calls base.setf(ios_base::hex, ios_base::basefield).
inline ios_base&
hex(ios_base& __base)
{
__base.setf(ios_base::hex, ios_base::basefield);
return __base;
}
/// Calls base.setf(ios_base::oct, ios_base::basefield).
inline ios_base&
oct(ios_base& __base)
{
__base.setf(ios_base::oct, ios_base::basefield);
return __base;
}
// [27.4.5.4] floatfield manipulators
/// Calls base.setf(ios_base::fixed, ios_base::floatfield).
inline ios_base&
fixed(ios_base& __base)
{
__base.setf(ios_base::fixed, ios_base::floatfield);
return __base;
}
/// Calls base.setf(ios_base::scientific, ios_base::floatfield).
inline ios_base&
scientific(ios_base& __base)
{
__base.setf(ios_base::scientific, ios_base::floatfield);
return __base;
}
#if __cplusplus >= 201103L
// New C++11 floatfield manipulators
/// Calls
/// base.setf(ios_base::fixed|ios_base::scientific, ios_base::floatfield)
inline ios_base&
hexfloat(ios_base& __base)
{
__base.setf(ios_base::fixed | ios_base::scientific, ios_base::floatfield);
return __base;
}
/// Calls @c base.unsetf(ios_base::floatfield)
inline ios_base&
defaultfloat(ios_base& __base)
{
__base.unsetf(ios_base::floatfield);
return __base;
}
#endif
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace
#endif /* _IOS_BASE_H */
iconv 库的使用
#include <stdio.h> //标准输入输出头文件
#include <sys/stat.h> //stat结构体和stat函数所在的头文件
#include <sys/types.h> //*本系统数据类型
#include <iconv.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
/**利用stat函数和stat结构体获取普通文件的长度
* 不用打开文件,访问文件的实际数据部分,只需访问文件的inode节点
* 效率较前面一个函数高
* 可以通过struct stat判断文件是否为普通文件,避免目录
* 成功返回长度,失败返回-1
* */
off_t get_flen(char *file_path)
{
struct stat st_buffer;
int err = stat(file_path,&st_buffer);
if(err != 0 || !S_ISREG(st_buffer.st_mode))
{
perror("读取文件状态出错或文件不是普通文件");
return -1;
}
return st_buffer.st_size;
}
char *to_utf(char *src, size_t src_len,const char * toencode,const char *fromencode)
{
iconv_t cptr = iconv_open(toencode,fromencode);
if(cptr == (iconv_t)-1)
{
printf("并不支持这种方式\n");
return NULL;
}
size_t out_len = 2 * src_len;
char *out = (char *)malloc(out_len);
if(out == NULL)
{
iconv_close(cptr);
return NULL;
}
memset(out,0,out_len);
char *dest = out;
size_t err = -1;
size_t inlen = src_len;
char *in = src;
err = iconv(cptr,&in,&inlen,&out,&out_len);
if(err != (size_t)-1 )
{
iconv_close(cptr);
return dest;
}
free(dest);
iconv_close(cptr);
return NULL;
}
int main(int argc, char *argv[])
{
off_t len = get_flen(argv[1]);
if(len == -1)
return -1;
printf("文件的长度为:%zd\n",len);
FILE *fp = fopen(argv[1],"r");
if(fp == NULL)
{
printf("文件打开失败!\n");
return -1;
}
void *src = NULL;
src = calloc(1, len + 1);
if(src == NULL)
{
fclose(fp);
return -1;
}
void *src_s = src;
if((size_t)len != fread(src,1,len,fp))
{
printf("读取文件有问题\n");
free(src_s);
fclose(fp);
return -1;
}
printf("文件中转换前为:%s\n",src);
//上面的代码都是从文件读入字符
char *out = NULL;
out = to_utf((char *)src,(size_t)len,"UTF-8","UCS-2");
free(src_s);
if(out == NULL)
{
fclose(fp);
return -1;
}
printf("转换后为:%s\n",out);
fclose(fp);
free(out);
return 0;
}
- 字符编码知识简介和iconv函数的简单使用 - 青儿哥哥 - 博客园 (cnblogs.com)
- libiconv - GNU Project - Free Software Foundation (FSF)
iconv for cpp
iconvpp: wrapper library of iconv for c++ (github.com)
basic_streambuf
// Stream buffer classes -*- C++ -*-
// Copyright (C) 1997-2018 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file include/streambuf
* This is a Standard C++ Library header.
*/
//
// ISO C++ 14882: 27.5 Stream buffers
//
#ifndef _GLIBXX_STREAMBUF
#define _GLIBXX_STREAMBUF 1
#pragma GCC system_header
#include <bits/c++config.h>
#include <iosfwd>
#include <bits/localefwd.h>
#include <bits/ios_base.h>
#include <bits/cpp_type_traits.h>
#include <ext/type_traits.h>
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
#define _IsUnused __attribute__ ((__unused__))
/**
* @brief The actual work of input and output (interface).
* @ingroup io
*
* @tparam _CharT Type of character stream.
* @tparam _Traits Traits for character type, defaults to
* char_traits<_CharT>.
*
* This is a base class. Derived stream buffers each control a
* pair of character sequences: one for input, and one for output.
*
* Section [27.5.1] of the standard describes the requirements and
* behavior of stream buffer classes. That section (three paragraphs)
* is reproduced here, for simplicity and accuracy.
*
* -# Stream buffers can impose various constraints on the sequences
* they control. Some constraints are:
* - The controlled input sequence can be not readable.
* - The controlled output sequence can be not writable.
* - The controlled sequences can be associated with the contents of
* other representations for character sequences, such as external
* files.
* - The controlled sequences can support operations @e directly to or
* from associated sequences.
* - The controlled sequences can impose limitations on how the
* program can read characters from a sequence, write characters to
* a sequence, put characters back into an input sequence, or alter
* the stream position.
* .
* -# Each sequence is characterized by three pointers which, if non-null,
* all point into the same @c charT array object. The array object
* represents, at any moment, a (sub)sequence of characters from the
* sequence. Operations performed on a sequence alter the values
* stored in these pointers, perform reads and writes directly to or
* from associated sequences, and alter <em>the stream position</em> and
* conversion state as needed to maintain this subsequence relationship.
* The three pointers are:
* - the <em>beginning pointer</em>, or lowest element address in the
* array (called @e xbeg here);
* - the <em>next pointer</em>, or next element address that is a
* current candidate for reading or writing (called @e xnext here);
* - the <em>end pointer</em>, or first element address beyond the
* end of the array (called @e xend here).
* .
* -# The following semantic constraints shall always apply for any set
* of three pointers for a sequence, using the pointer names given
* immediately above:
* - If @e xnext is not a null pointer, then @e xbeg and @e xend shall
* also be non-null pointers into the same @c charT array, as
* described above; otherwise, @e xbeg and @e xend shall also be null.
* - If @e xnext is not a null pointer and @e xnext < @e xend for an
* output sequence, then a <em>write position</em> is available.
* In this case, @e *xnext shall be assignable as the next element
* to write (to put, or to store a character value, into the sequence).
* - If @e xnext is not a null pointer and @e xbeg < @e xnext for an
* input sequence, then a <em>putback position</em> is available.
* In this case, @e xnext[-1] shall have a defined value and is the
* next (preceding) element to store a character that is put back
* into the input sequence.
* - If @e xnext is not a null pointer and @e xnext< @e xend for an
* input sequence, then a <em>read position</em> is available.
* In this case, @e *xnext shall have a defined value and is the
* next element to read (to get, or to obtain a character value,
* from the sequence).
*/
template<typename _CharT, typename _Traits>
class basic_streambuf
{
public:
//@{
/**
* These are standard types. They permit a standardized way of
* referring to names of (or names dependent on) the template
* parameters, which are specific to the implementation.
*/
typedef _CharT char_type;
typedef _Traits traits_type;
typedef typename traits_type::int_type int_type;
typedef typename traits_type::pos_type pos_type;
typedef typename traits_type::off_type off_type;
//@}
//@{
/// This is a non-standard type.
typedef basic_streambuf<char_type, traits_type> __streambuf_type;
//@}
friend class basic_ios<char_type, traits_type>;
friend class basic_istream<char_type, traits_type>;
friend class basic_ostream<char_type, traits_type>;
friend class istreambuf_iterator<char_type, traits_type>;
friend class ostreambuf_iterator<char_type, traits_type>;
protected:
/*
* This is based on _IO_FILE, just reordered to be more consistent,
* and is intended to be the most minimal abstraction for an
* internal buffer.
* - get == input == read
* - put == output == write
*/
char_type* _M_in_beg; ///< Start of get area.
char_type* _M_in_cur; ///< Current read area.
char_type* _M_in_end; ///< End of get area.
char_type* _M_out_beg; ///< Start of put area.
char_type* _M_out_cur; ///< Current put area.
char_type* _M_out_end; ///< End of put area.
/// Current locale setting.
locale _M_buf_locale;
public:
/// Destructor deallocates no buffer space.
virtual
~basic_streambuf()
{ }
/**
* @brief Entry points for derived buffer functions.
*
* The public versions of @c pubfoo dispatch to the protected
* derived @c foo member functions, passing the arguments (if any)
* and returning the result unchanged.
*/
basic_streambuf*
pubsetbuf(char_type* __s, streamsize __n)
{ return this->setbuf(__s, __n); }
/**
* @brief Alters the stream position.
* @param __off Offset.
* @param __way Value for ios_base::seekdir.
* @param __mode Value for ios_base::openmode.
*
* Calls virtual seekoff function.
*/
pos_type
pubseekoff(off_type __off, ios_base::seekdir __way,
ios_base::openmode __mode = ios_base::in | ios_base::out)
{ return this->seekoff(__off, __way, __mode); }
/**
* @brief Alters the stream position.
* @param __sp Position
* @param __mode Value for ios_base::openmode.
*
* Calls virtual seekpos function.
*/
pos_type
pubseekpos(pos_type __sp,
ios_base::openmode __mode = ios_base::in | ios_base::out)
{ return this->seekpos(__sp, __mode); }
/**
* @brief Calls virtual sync function.
*/
int
pubsync() { return this->sync(); }
//@}
// [27.5.2.2.3] get area
/**
* @brief Looking ahead into the stream.
* @return The number of characters available.
*
* If a read position is available, returns the number of characters
* available for reading before the buffer must be refilled.
* Otherwise returns the derived @c showmanyc().
*/
streamsize
in_avail()
{
const streamsize __ret = this->egptr() - this->gptr();
return __ret ? __ret : this->showmanyc();
}
/**
* @brief Getting the next character.
* @return The next character, or eof.
*
* Calls @c sbumpc(), and if that function returns
* @c traits::eof(), so does this function. Otherwise, @c sgetc().
*/
int_type
snextc()
{
int_type __ret = traits_type::eof();
if (__builtin_expect(!traits_type::eq_int_type(this->sbumpc(),
__ret), true))
__ret = this->sgetc();
return __ret;
}
/**
* @brief Getting the next character.
* @return The next character, or eof.
*
* If the input read position is available, returns that character
* and increments the read pointer, otherwise calls and returns
* @c uflow().
*/
int_type
sbumpc()
{
int_type __ret;
if (__builtin_expect(this->gptr() < this->egptr(), true))
{
__ret = traits_type::to_int_type(*this->gptr());
this->gbump(1);
}
else
__ret = this->uflow();
return __ret;
}
/**
* @brief Getting the next character.
* @return The next character, or eof.
*
* If the input read position is available, returns that character,
* otherwise calls and returns @c underflow(). Does not move the
* read position after fetching the character.
*/
int_type
sgetc()
{
int_type __ret;
if (__builtin_expect(this->gptr() < this->egptr(), true))
__ret = traits_type::to_int_type(*this->gptr());
else
__ret = this->underflow();
return __ret;
}
/**
* @brief Entry point for xsgetn.
* @param __s A buffer area.
* @param __n A count.
*
* Returns xsgetn(__s,__n). The effect is to fill @a __s[0] through
* @a __s[__n-1] with characters from the input sequence, if possible.
*/
streamsize
sgetn(char_type* __s, streamsize __n)
{ return this->xsgetn(__s, __n); }
// [27.5.2.2.4] putback
/**
* @brief Pushing characters back into the input stream.
* @param __c The character to push back.
* @return The previous character, if possible.
*
* Similar to sungetc(), but @a __c is pushed onto the stream
* instead of <em>the previous character.</em> If successful,
* the next character fetched from the input stream will be @a
* __c.
*/
int_type
sputbackc(char_type __c)
{
int_type __ret;
const bool __testpos = this->eback() < this->gptr();
if (__builtin_expect(!__testpos ||
!traits_type::eq(__c, this->gptr()[-1]), false))
__ret = this->pbackfail(traits_type::to_int_type(__c));
else
{
this->gbump(-1);
__ret = traits_type::to_int_type(*this->gptr());
}
return __ret;
}
/**
* @brief Moving backwards in the input stream.
* @return The previous character, if possible.
*
* If a putback position is available, this function decrements
* the input pointer and returns that character. Otherwise,
* calls and returns pbackfail(). The effect is to @a unget
* the last character @a gotten.
*/
int_type
sungetc()
{
int_type __ret;
if (__builtin_expect(this->eback() < this->gptr(), true))
{
this->gbump(-1);
__ret = traits_type::to_int_type(*this->gptr());
}
else
__ret = this->pbackfail();
return __ret;
}
// [27.5.2.2.5] put area
/**
* @brief Entry point for all single-character output functions.
* @param __c A character to output.
* @return @a __c, if possible.
*
* One of two public output functions.
*
* If a write position is available for the output sequence (i.e.,
* the buffer is not full), stores @a __c in that position, increments
* the position, and returns @c traits::to_int_type(__c). If a write
* position is not available, returns @c overflow(__c).
*/
int_type
sputc(char_type __c)
{
int_type __ret;
if (__builtin_expect(this->pptr() < this->epptr(), true))
{
*this->pptr() = __c;
this->pbump(1);
__ret = traits_type::to_int_type(__c);
}
else
__ret = this->overflow(traits_type::to_int_type(__c));
return __ret;
}
/**
* @brief Entry point for all single-character output functions.
* @param __s A buffer read area.
* @param __n A count.
*
* One of two public output functions.
*
*
* Returns xsputn(__s,__n). The effect is to write @a __s[0] through
* @a __s[__n-1] to the output sequence, if possible.
*/
streamsize
sputn(const char_type* __s, streamsize __n)
{ return this->xsputn(__s, __n); }
protected:
/**
* @brief Base constructor.
*
* Only called from derived constructors, and sets up all the
* buffer data to zero, including the pointers described in the
* basic_streambuf class description. Note that, as a result,
* - the class starts with no read nor write positions available,
* - this is not an error
*/
basic_streambuf()
: _M_in_beg(0), _M_in_cur(0), _M_in_end(0),
_M_out_beg(0), _M_out_cur(0), _M_out_end(0),
_M_buf_locale(locale())
{ }
// [27.5.2.3.1] get area access
//@{
/**
* @brief Access to the get area.
*
* These functions are only available to other protected functions,
* including derived classes.
*
* - eback() returns the beginning pointer for the input sequence
* - gptr() returns the next pointer for the input sequence
* - egptr() returns the end pointer for the input sequence
*/
char_type*
eback() const { return _M_in_beg; }
char_type*
gptr() const { return _M_in_cur; }
char_type*
egptr() const { return _M_in_end; }
//@}
/**
* @brief Moving the read position.
* @param __n The delta by which to move.
*
* This just advances the read position without returning any data.
*/
void
gbump(int __n) { _M_in_cur += __n; }
/**
* @brief Setting the three read area pointers.
* @param __gbeg A pointer.
* @param __gnext A pointer.
* @param __gend A pointer.
* @post @a __gbeg == @c eback(), @a __gnext == @c gptr(), and
* @a __gend == @c egptr()
*/
void
setg(char_type* __gbeg, char_type* __gnext, char_type* __gend)
{
_M_in_beg = __gbeg;
_M_in_cur = __gnext;
_M_in_end = __gend;
}
// [27.5.2.3.2] put area access
//@{
/**
* @brief Access to the put area.
*
* These functions are only available to other protected functions,
* including derived classes.
*
* - pbase() returns the beginning pointer for the output sequence
* - pptr() returns the next pointer for the output sequence
* - epptr() returns the end pointer for the output sequence
*/
char_type*
pbase() const { return _M_out_beg; }
char_type*
pptr() const { return _M_out_cur; }
char_type*
epptr() const { return _M_out_end; }
//@}
/**
* @brief Moving the write position.
* @param __n The delta by which to move.
*
* This just advances the write position without returning any data.
*/
void
pbump(int __n) { _M_out_cur += __n; }
/**
* @brief Setting the three write area pointers.
* @param __pbeg A pointer.
* @param __pend A pointer.
* @post @a __pbeg == @c pbase(), @a __pbeg == @c pptr(), and
* @a __pend == @c epptr()
*/
void
setp(char_type* __pbeg, char_type* __pend)
{
_M_out_beg = _M_out_cur = __pbeg;
_M_out_end = __pend;
}
// [27.5.2.4] virtual functions
// [27.5.2.4.1] locales
/**
* @brief Changes translations.
* @param __loc A new locale.
*
* Translations done during I/O which depend on the current
* locale are changed by this call. The standard adds,
* <em>Between invocations of this function a class derived
* from streambuf can safely cache results of calls to locale
* functions and to members of facets so obtained.</em>
*
* @note Base class version does nothing.
*/
virtual void
imbue(const locale& __loc _IsUnused)
{ }
// [27.5.2.4.2] buffer management and positioning
/**
* @brief Manipulates the buffer.
*
* Each derived class provides its own appropriate behavior. See
* the next-to-last paragraph of
* https://gcc.gnu.org/onlinedocs/libstdc++/manual/streambufs.html#io.streambuf.buffering
* for more on this function.
*
* @note Base class version does nothing, returns @c this.
*/
virtual basic_streambuf<char_type,_Traits>*
setbuf(char_type*, streamsize)
{ return this; }
/**
* @brief Alters the stream positions.
*
* Each derived class provides its own appropriate behavior.
* @note Base class version does nothing, returns a @c pos_type
* that represents an invalid stream position.
*/
virtual pos_type
seekoff(off_type, ios_base::seekdir,
ios_base::openmode /*__mode*/ = ios_base::in | ios_base::out)
{ return pos_type(off_type(-1)); }
/**
* @brief Alters the stream positions.
*
* Each derived class provides its own appropriate behavior.
* @note Base class version does nothing, returns a @c pos_type
* that represents an invalid stream position.
*/
virtual pos_type
seekpos(pos_type,
ios_base::openmode /*__mode*/ = ios_base::in | ios_base::out)
{ return pos_type(off_type(-1)); }
/**
* @brief Synchronizes the buffer arrays with the controlled sequences.
* @return -1 on failure.
*
* Each derived class provides its own appropriate behavior,
* including the definition of @a failure.
* @note Base class version does nothing, returns zero.
*/
virtual int
sync() { return 0; }
// [27.5.2.4.3] get area
/**
* @brief Investigating the data available.
* @return An estimate of the number of characters available in the
* input sequence, or -1.
*
* <em>If it returns a positive value, then successive calls to
* @c underflow() will not return @c traits::eof() until at
* least that number of characters have been supplied. If @c
* showmanyc() returns -1, then calls to @c underflow() or @c
* uflow() will fail.</em> [27.5.2.4.3]/1
*
* @note Base class version does nothing, returns zero.
* @note The standard adds that <em>the intention is not only that the
* calls [to underflow or uflow] will not return @c eof() but
* that they will return immediately.</em>
* @note The standard adds that <em>the morphemes of @c showmanyc are
* @b es-how-many-see, not @b show-manic.</em>
*/
virtual streamsize
showmanyc() { return 0; }
/**
* @brief Multiple character extraction.
* @param __s A buffer area.
* @param __n Maximum number of characters to assign.
* @return The number of characters assigned.
*
* Fills @a __s[0] through @a __s[__n-1] with characters from the input
* sequence, as if by @c sbumpc(). Stops when either @a __n characters
* have been copied, or when @c traits::eof() would be copied.
*
* It is expected that derived classes provide a more efficient
* implementation by overriding this definition.
*/
virtual streamsize
xsgetn(char_type* __s, streamsize __n);
/**
* @brief Fetches more data from the controlled sequence.
* @return The first character from the <em>pending sequence</em>.
*
* Informally, this function is called when the input buffer is
* exhausted (or does not exist, as buffering need not actually be
* done). If a buffer exists, it is @a refilled. In either case, the
* next available character is returned, or @c traits::eof() to
* indicate a null pending sequence.
*
* For a formal definition of the pending sequence, see a good text
* such as Langer & Kreft, or [27.5.2.4.3]/7-14.
*
* A functioning input streambuf can be created by overriding only
* this function (no buffer area will be used). For an example, see
* https://gcc.gnu.org/onlinedocs/libstdc++/manual/streambufs.html
*
* @note Base class version does nothing, returns eof().
*/
virtual int_type
underflow()
{ return traits_type::eof(); }
/**
* @brief Fetches more data from the controlled sequence.
* @return The first character from the <em>pending sequence</em>.
*
* Informally, this function does the same thing as @c underflow(),
* and in fact is required to call that function. It also returns
* the new character, like @c underflow() does. However, this
* function also moves the read position forward by one.
*/
virtual int_type
uflow()
{
int_type __ret = traits_type::eof();
const bool __testeof = traits_type::eq_int_type(this->underflow(),
__ret);
if (!__testeof)
{
__ret = traits_type::to_int_type(*this->gptr());
this->gbump(1);
}
return __ret;
}
// [27.5.2.4.4] putback
/**
* @brief Tries to back up the input sequence.
* @param __c The character to be inserted back into the sequence.
* @return eof() on failure, <em>some other value</em> on success
* @post The constraints of @c gptr(), @c eback(), and @c pptr()
* are the same as for @c underflow().
*
* @note Base class version does nothing, returns eof().
*/
virtual int_type
pbackfail(int_type __c _IsUnused = traits_type::eof())
{ return traits_type::eof(); }
// Put area:
/**
* @brief Multiple character insertion.
* @param __s A buffer area.
* @param __n Maximum number of characters to write.
* @return The number of characters written.
*
* Writes @a __s[0] through @a __s[__n-1] to the output sequence, as if
* by @c sputc(). Stops when either @a n characters have been
* copied, or when @c sputc() would return @c traits::eof().
*
* It is expected that derived classes provide a more efficient
* implementation by overriding this definition.
*/
virtual streamsize
xsputn(const char_type* __s, streamsize __n);
/**
* @brief Consumes data from the buffer; writes to the
* controlled sequence.
* @param __c An additional character to consume.
* @return eof() to indicate failure, something else (usually
* @a __c, or not_eof())
*
* Informally, this function is called when the output buffer
* is full (or does not exist, as buffering need not actually
* be done). If a buffer exists, it is @a consumed, with
* <em>some effect</em> on the controlled sequence.
* (Typically, the buffer is written out to the sequence
* verbatim.) In either case, the character @a c is also
* written out, if @a __c is not @c eof().
*
* For a formal definition of this function, see a good text
* such as Langer & Kreft, or [27.5.2.4.5]/3-7.
*
* A functioning output streambuf can be created by overriding only
* this function (no buffer area will be used).
*
* @note Base class version does nothing, returns eof().
*/
virtual int_type
overflow(int_type __c _IsUnused = traits_type::eof())
{ return traits_type::eof(); }
#if _GLIBCXX_USE_DEPRECATED && __cplusplus <= 201402L
// Annex D.6 (removed in C++17)
public:
/**
* @brief Tosses a character.
*
* Advances the read pointer, ignoring the character that would have
* been read.
*
* See http://gcc.gnu.org/ml/libstdc++/2002-05/msg00168.html
*/
#if __cplusplus >= 201103L
[[__deprecated__("stossc is deprecated, use sbumpc instead")]]
#endif
void
stossc()
{
if (this->gptr() < this->egptr())
this->gbump(1);
else
this->uflow();
}
#endif
// Also used by specializations for char and wchar_t in src.
void
__safe_gbump(streamsize __n) { _M_in_cur += __n; }
void
__safe_pbump(streamsize __n) { _M_out_cur += __n; }
#if __cplusplus < 201103L
private:
#else
protected:
#endif
basic_streambuf(const basic_streambuf&);
basic_streambuf&
operator=(const basic_streambuf&);
#if __cplusplus >= 201103L
void
swap(basic_streambuf& __sb)
{
std::swap(_M_in_beg, __sb._M_in_beg);
std::swap(_M_in_cur, __sb._M_in_cur);
std::swap(_M_in_end, __sb._M_in_end);
std::swap(_M_out_beg, __sb._M_out_beg);
std::swap(_M_out_cur, __sb._M_out_cur);
std::swap(_M_out_end, __sb._M_out_end);
std::swap(_M_buf_locale, __sb._M_buf_locale);
}
#endif
};
#if __cplusplus >= 201103L
template<typename _CharT, typename _Traits>
std::basic_streambuf<_CharT, _Traits>::
basic_streambuf(const basic_streambuf&) = default;
template<typename _CharT, typename _Traits>
std::basic_streambuf<_CharT, _Traits>&
std::basic_streambuf<_CharT, _Traits>::
operator=(const basic_streambuf&) = default;
#endif
// Explicit specialization declarations, defined in src/streambuf.cc.
template<>
streamsize
__copy_streambufs_eof(basic_streambuf<char>* __sbin,
basic_streambuf<char>* __sbout, bool& __ineof);
#ifdef _GLIBCXX_USE_WCHAR_T
template<>
streamsize
__copy_streambufs_eof(basic_streambuf<wchar_t>* __sbin,
basic_streambuf<wchar_t>* __sbout, bool& __ineof);
#endif
#undef _IsUnused
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace
#include <bits/streambuf.tcc>
#endif /* _GLIBCXX_STREAMBUF */