将文件的未知部分读取到矢量

时间:2016-06-02 10:14:16

标签: c++

我想打开一个文件,读取前5个字节,检查前4个匹配给定签名,第5个是我文件头的大小。标题的大小是我接下来要读取的其他数据的构建。

到目前为止我尝试了什么:

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

typedef struct file_header{
    char signature[4];
    unsigned char size;
    char version;
    //Different other things left out for example matters.
    unsigned int blocks;
    unsigned int block_size;
} header;

void open_file(std::string fileName, header &header){
    std::ifstream fIn;
    fIn.exceptions(std::ifstream::failbit | std::ifstream::badbit);
    char buffer[5];
    try{
        fIn.open(fileName, std::ios::binary);
        //read the 1st 5 bytes to get header signature and header size
        fIn.read(buffer, 5);
        header.size = buffer[4];

        //Here my problems begins...
        fIn.seekg(0, std::ios::beg);
        std::vector<char*> header_data;
        header_data.reserve((int)header.size);

        //How do i read the first (int)header.size bytes of file to Vector?
        fIn.read(header_data[0], (int)header.size); //Wont work?

    }catch(std::ifstream::failure ex){
        std::cerr << ex.code().message() << std::endl;
        exit(0);
    }
}

int main(int argc, char* argv[]){
    char* filename = argv[1];
    file_header header;
    open_file(filename, header);
    return 0;
}

我刚刚开始使用c ++,但在Java中,我可以做一些整洁的事情:

char header_size[(int)header.size];

但是到目前为止我发现的是,你不能在c ++中制作动态数组,因此也就是向量。

我能做些什么来获得我需要的输出?

我写的代码给出了一个超出范围的Vector,我猜[0]会这样做吗?

任何帮助或指示已经被发现..

2 个答案:

答案 0 :(得分:0)

您应该执行@"Data Source=C:\Users\MYPC\Documents\Visual Studio 2010\Projects\MyProjectFolder\MyProject-1\bin\Debug\MyDatabase.sdf;Persist Security Info=False;";,因为vector_data.resize(header.size)只保留内存,这并不意味着此向量包含有效对象(因此您无法访问任何内容)

请参阅this SO question,了解reservestd::vector<T>::resize之间的区别。

此外,您正在为std::vector<T>::reserve类型的header.size元素分配内存,但所有元素都未初始化,所以当您尝试读取其中一个元素时,您将无处可读,这将导致分段错误。首先使用char *为每个指针分配内存。

答案 1 :(得分:0)

一旦您读取了标题,文件指针就会准备好读取它后面的字节。 fIn.seekg(0, std::ios::beg);会将文件指针移回到您不想要的开头。

fIn.read(buffer, 5);
header.size = buffer[4];
char * header_data = new char[header.size];
fIn.read(header_data, (streamsize)header.size);

当你完成它时,你必须释放分配给header_data的内存

delete[] header_data;
相关问题