简体   繁体   中英

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++?

use the read or readsome function in istream . eg

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

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

将函数定义更改为此(注意&符号):

string read_two_bytes(fstream & file)

@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, iostream s 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++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM