CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    May 2002
    Posts
    1,798

    How to scan file bytes using istreambuf_iterator<unsigned char> iit(f);

    Phil Nicolletti posted this code to load a section of a text file given an open fstream, starting and ending points:
    Code:
    /// Suggested by Phil Nicolleti : http://www.codeguru.com/forum/showthread.php?t=473898
    /// Modified by Mike Pliam August 19, 2014 for single byte file streams.
    vector<char> GetBytes(ifstream &f, long ustart, long uend)
    {
    	vector<char> vb;
    	const long nsz = (uend-ustart)/2;
    	vb.resize(nsz); //vb = 0x00;
    	if(!f.is_open()) { _RPT0(0, "No stream available in GetBytes.\n"); return vb; }
    
    	if(ustart < 0 || uend < ustart) return vb; 
    
    
    	f.clear();
    	f.seekg(ustart);
    
    	istreambuf_iterator<char> iit(f);
    	//std::istreambuf_iterator<char> iit (std::cin.rdbuf()); // stdin iterator
      
    	for(int ul = 0; ul < nsz; ul++) 
    	{
    		vb[ul] = *iit++; 
    	}
    
    	return vb;
    
    }// GetBytes(ifstream &f, long ustart, long uend)
    But now I want to load a section of bytes (unsigned char) rather than char. Unfortunately, I cannot get to cooperate:
    Code:
     istreambuf_iterator<unsigned char> iit(f);
    .

    Error is:
    error C2664: 'std::istreambuf_iterator<_Elem>::istreambuf_iterator(std::basic_streambuf<_Elem,_Traits> *) throw()' :
    cannot convert parameter 1 from 'std::ifstream' to 'std::basic_streambuf<_Elem,_Traits> *'
    I need bytes, not chars. Help appreciated.
    mpliam

  2. #2
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: How to scan file bytes using istreambuf_iterator<unsigned char> iit(f);

    Quote Originally Posted by Mike Pliam
    I need bytes, not chars.
    char, signed char and unsigned char can all be used to store "bytes", but the latter tends to be the best option when you will do things like bit shifting.

    Quote Originally Posted by Mike Pliam
    But now I want to load a section of bytes (unsigned char) rather than char. Unfortunately, I cannot get to cooperate:
    You may need to use std::istream_iterator instead of std::istreambuf_iterator, but I'm not sure how that might affect the efficiency. Alternatively, you could switch the std::vector<unsigned char>, but leave it as std::istreambuf_iterator<char> since whether char is signed or unsigned, the conversion to unsigned char will be safe.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured