read part of a file with iostreams

后端 未结 3 932
忘了有多久
忘了有多久 2021-02-15 14:18

Can I open an ifstream (or set an existing one in any way) to only read part of a file? For example, I would like to have my ifstream read a file from

3条回答
  •  生来不讨喜
    2021-02-15 15:01

    You could read the bytes that you want into a string or char array, then you can use that string with a istringstream, and use that instead of your ifstream. Example:

    std::ifstream fin("foo.txt");
    fin.seekg(10);
    char buffer[41];
    fin.read(buffer, 40);
    buffer[40] = 0;
    std::istringstream iss(buffer);
    for (std::string s; iss >> s; ) std::cout << s << '\n';
    

    If you need to handle binary files, you can do that too:

    std::ifstream fin("foo.bin", std::ios::binary | std::ios::in);
    fin.seekg(10);
    char buffer[40];
    fin.read(buffer, 40);
    std::istringstream(std::string(buffer, buffer+40));
    

提交回复
热议问题