P.S. , ... - .
, Linux, "?
:.
% printf 'D\x00C\x00\x00B\x00A' | sort -z | od -c
0000000 \0 A \0 B \0 C \0 D \0
0000011
FSF/GNU -z:
-z,
end lines with 0 byte, not newline
:
, , ...
, STL.
struct FUNCTOR ( stl:: sort()). , , ostream_iterator <string> (cout, "\n" ), .
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;
inline bool
IsStreamStillGood( istream & theStream )
{
return theStream && (theStream . peek() != EOF);
}
template<class TYPE> inline void DELETE( TYPE * x)
{
delete x;
x = (TYPE *) NULL;
}
struct FUNCTOR
{
bool operator()(const string & x, const string & y) { return x < y; }
};
int
main(int argc, char **argv)
{
istream * stream;
vector<string> v;
UASSERT( argc, >, 1 );
const int recordSize = atoi( argv[1] );
char buffer [ recordSize + 1 ];
UASSERT( recordSize, >, 0 );
if ( argc > 2 )
stream = new ifstream( argv[2] );
else
stream = & cin;
while ( IsStreamStillGood( * stream ) )
{
stream-> read( buffer, recordSize );
v.push_back( string( buffer, stream->gcount() ) );
}
UASSERT( v.back().size(), ==, size_t(recordSize) );
FUNCTOR functor;
sort( v.begin(), v.end(), functor );
copy( v.begin(), v.end(), ostream_iterator<string>(cout) );
if ( argc > 2 )
DELETE(stream);
}
(), :
STL-: ('\ 0'), - ? - char [], , .
char c [10];, c [0] = '\ 0';. c [1] c [9]. , . ( , , .)
c c- , . 1 9? C , NULL.
, printf (% s), scanf (% s), strncat(), strncpy(), strncmp() .., NULL ('\ 0'), .
++ std::string . , , , : myString.append(10, '\ 0');
, stream- > read (buffer, recordSize), (). , ('\ 0') . . recordSize .
v.push_back (string (buffer, stream- > gcount())), , stream- > gcount() (). , ('\ 0') . stream- > gcount() .
, < (const string &, const string &), string:: compare(), , . Nulls ('\ 0') .
Now, if we try to use v.back (). c_str (), well, then we have no length, so the zeros will confuse us. But while we are using a string object (e.g. v.back ()) containing both data and length, we are good.
This leads us to a conclusion. And again we print the string, not myString.c_str (), so all the characters in the string are printed. Zeros ('\ 0') are included.