0

Нужно пройтись по файлу 2 раза, чтоб узнать его размер, а потом прочитать. Проблема в том, что seekg(0) не сбрасывает указатель на элемент файла функции get и во втором цикле она сразу возвращает false. как это исправить?

int main()
{
    fstream file("/home/anton/Загрузки/Сайт/content/nodemcu.jpg");
    std::string buffer;
    char current;
    int size;
    while(file.get(current))
    {
        size++;
    }
    file.seekg(0);
    while (file.get(current))
    {
        buffer.push_back(current);
    }
    cout << buffer.length();
    file.close();
}

2 ответа 2

1

Вместо чтения файла до упора (что выставит флажок eof) открывайте файл в бинарном режиме отмотанным в конец и получайте размер:

::std::ifstream file{"/home/anton/Загрузки/Сайт/content/nodemcu.jpg", ::std::ifstream::ate bitor ::std::ifstream::binary};
auto const size{file.tellg()};
file.seekg(0);
3
  • а для чего это нужно ::std::ifstream::ate bitor ::std::ifstream::binary ? 24 дек 2019 в 17:59
  • @DenverToha, это анология ::std::ifstream::ate | ::std::ifstream::binary
    – user206435
    24 дек 2019 в 18:02
  • @DenverToha ate - это открыть с перемоткой в конец, binary - открыть в бинарном режиме 24 дек 2019 в 19:03
0

Если Вам нужен размер файла в stl из boost перекочевала filesystem

#include <iostream>
#include <filesystem>
#include <cstdint>
#include <stdio.h>


int main() {

    auto path{ std::filesystem::current_path() / "data" };
    try {
        if (!std::filesystem::exists(path)) {
            throw std::runtime_error{ "Error : file not found" };
        } else {
            std::uintmax_t size{ std::filesystem::file_size("data") };
            std::cout << "Size : " << size << std::endl;
        }
    } catch (std::filesystem::filesystem_error & e) {
        std::cout << e.what() << '\n';
    }

    // Старый стиль
    FILE* f;
    auto f_r = fopen("data", "r");
    fseek(f_r, 0L, SEEK_END);
    auto c_size = ftell(f_r);

    std::cout << "File size : " << c_size << std::endl;
    fseek(f_r, 0L, SEEK_SET);

    return 0;
}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.