繁体   English   中英

如何存储以二进制模式C ++读取的文件中的数据

[英]How to store data from a file read in binary mode C++

嗨,我正在尝试读取文件,例如'sample.txt',在二进制模式-c ++中,我需要将文件文本(例如“nodeA nodeB”)存储在向量中。 例如:“AABEABG”如果这是文本文件中的内容,我想以二进制形式读取它,然后将其存储在某个变量中,然后对它进行一些操作。 任何帮助,将不胜感激。 到目前为止我得到的是:

int main () {
  streampos begin,end;
  ifstream myfile ("example.bin", ios::binary);
  begin = myfile.tellg();
  myfile.seekg (0, ios::end);
  end = myfile.tellg();
  myfile.close();
  cout << "size is: " << (end-begin) << " bytes.\n";
  return 0;
}

myfile文件中的文本部分可以得到怎么样?

您接下来的方法是ifstream::read(char *,streamsize) 获得文件大小(以字节为单位)后,您可以将数据读入正确大小的vector<char> (在回到文件开头之后):

streamsize n=end-begin;
vector<char> data((size_t)n);

myfile.seekg(0,ios::beg);
myfile.read(&data[0],n);

vector<char>的迭代器类型可能不一定是char *指针,因此我们作为第一个参数传递,以读取指向vector的第一个元素的指针。 std::vector的元素保证连续布局,因此我们可以确保写入&data[0]+k等效于&data[k] ,对于有效索引k。

您的文件sample.txt或其他任何内容都是文本文件。 我相信你想“以二进制形式阅读”,因为你认为你必须这样做才能找出数据的大小,这样你就可以在某个变量中分配那个大小的存储来包含数据。

在这种情况下,您真正​​要做的就是将文本文件读入合适的变量,并且您可以非常简单地执行此操作,而无需发现文件的长度:

#include <fstream>
#include <iterator>
#include <string>
#include <algorithm>

...

std::istream_iterator<char> eos; // An end-of-stream iterator
// Open your file
std::ifstream in("sample.txt"); 
if (!in) { // It didn't open for some reason.
    // So handle the error somehow and get out of here. 
}
// Your file opened OK
std::noskipws(in);  // You don't want to ignore whitespace when reading it
std::istream_iterator<char> in_iter(in); // An input-stream iterator for `in` 
std::string data;   // A string to store the data
std::copy(in_iter,eos,std::back_inserter(data)); // Copy the file to string

现在, sample.txt的全部内容都在字符串data ,您可以随意解析它。 你可以用一些其他标准容器类型的char替换std::string ,例如std::vector<char> ,这样就可以了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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