ghostmansd
ghostmansd

Reputation: 3465

Is there analog in C++ for Python's file.read(2)?

I'm currently trying to make analog of Python's function:

def read_two_symbols(fdescr):
 return(file.read(2))

myfile = open('mytext.txt', 'rb')
two_symbols = read_two_symbols(myfile)
print(two_symbols)

Is there any way to do it in C++? That's what I've tried:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

string read_two_bytes(fstream file)
{
  string byte1, byte2;
  byte1 = file.get();
  byte2 = file.get();
  string two_bytes = byte1 + byte2;
  return two_bytes;
}

int main()
{
  fstream myfile("mytext.txt", ios_base::in | ios_base::binary);
  string two_bytes = read_two_bytes(myfile);
  cout << two_bytes << endl;
  return 0;
}

However it fails. :-( How can I do it using C++?

Upvotes: 0

Views: 247

Answers (3)

@vivek has pointed out that you can't pass an fstream "by value". Passing things by value makes copies of them (or rather, runs their copy constructor, which may or may not actually make a "deep" copy of them).

Once you fix that, iostreams are actually cute and cuddly. They can detect the type you're asking for and read just that amount of data. If it's a char and you use the stream operators, it'll read a byte's worth:

string read_two_bytes(fstream& file)
{
  char byte1, byte2;
  file >> byte1 >> byte2;

  string two_bytes;
  two_bytes += byte1;
  two_bytes += byte2;

  return two_bytes;
}

@Nim seems to be trying to give you a generalized answer, perhaps to show off C++ vs Python. It's more answering the question for "N-bytes", except he hardcoded 2 so it just looks like overkill. It can be done easier, but nice to know the flexiblity is there...no?

If you're new to C++ I/O you might find the answer to this question I bothered to write the other day to be interesting as a contrast to the methods being suggested by other answers:

Output error when input isn't a number. C++

Upvotes: 1

vivek
vivek

Reputation: 5219

Change the function definition to this ( notice the & sign):

string read_two_bytes(fstream & file)

Upvotes: 1

Nim
Nim

Reputation: 33645

use the read or readsome function in istream. e.g

std::vector<char> buffer(2, 0);

if (myfile.read(&buffer[0], 2))
  std::copy(buffer.begin(), buffer.end(), std::ostream_iterator<int>(std::cout, ""));

Upvotes: 1

Related Questions