1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
|
#include <iostream>
#include <fstream>
#include <strstream> // deprecated
#include <cctype>
#include <locale>
#include <vector>
#include <string>
#include <ctime>
#include <windows.h>
#include <cassert>
#include <cstdio>
int main()
{
const char* const path = "test.txt" ;
{
std::ofstream file(path) ;
for( int i = 0 ; i < 1000 ; ++i ) file << std::ifstream( __FILE__ ).rdbuf() ;
}
const auto start = std::clock() ; // *** start timer
// using namespace boost::interprocess ;
// file_mapping mapping( path, read_only ) ;
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
HANDLE file = CreateFile( path, GENERIC_READ, 0, 0, OPEN_EXISTING,
FILE_FLAG_SEQUENTIAL_SCAN | FILE_FLAG_DELETE_ON_CLOSE, 0 ) ;
assert( file != INVALID_HANDLE_VALUE ) ;
// mapped_region region( mapping, read_only) ;
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa366537(v=vs.85).aspx
HANDLE mapping = CreateFileMapping( file, 0, PAGE_READONLY, 0, 0, 0 ) ;
assert(mapping) ;
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa366761(v=vs.85).aspx
const char* const address = static_cast< const char* >( MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 ) ) ;
assert(address) ;
// const std::size_t nbytes = region.get_size() ;
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa364955(v=vs.85).aspx
const DWORD nbytes = GetFileSize( file, 0 ) ;
std::istrstream stm( address, nbytes ) ; // deprecated
// This ctype facet classifies all punctuations too as whitespace
struct punct_too_is_ws : std::ctype<char>
{
static const mask* classification_table()
{
// start with the classic table ( C locale's table )
static std::vector<mask> table( classic_table(), classic_table() + table_size ) ;
// all punctuation is to be treated as whitespace
for( std::size_t i = 0 ; i < table_size ; ++i ) if( std::ispunct(i) ) table[i] = space ;
return std::addressof( table.front() ) ;
}
// do not delete table, initial reference count == 0
punct_too_is_ws() : std::ctype<char>( classification_table() ) {}
};
stm.imbue( std::locale( stm.getloc(), new punct_too_is_ws ) ) ;
std::string str ;
std::size_t cnt = 0 ;
while( stm >> str ) ++cnt ;
const auto end = std::clock() ; // *** end timer
std::cout << cnt << " words were read in " << double(end-start)*1000 / CLOCKS_PER_SEC << " milliseconds.\n" ;
// 340000 words were read in 109 milliseconds.
// UnmapViewOfFile, CloseHandle, CloseHandle ...
}
|