Чтение бинарных файлов и правильное использование потоковых итераторов

Я пытаюсь использовать этот вид итераторов, но у меня есть ошибки для следующего кода:

void linearMatrix::Write_File_Matrix(const char *Path)
{
ofstream FILE(Path, std::ios::out | std::ofstream::binary);
FILE.write(reinterpret_cast<const char *>(&myWidth), sizeof(float));
FILE.write(reinterpret_cast<const char *>(&myHeight), sizeof(float));
ostreambuf_iterator<float> out_it (FILE);
copy(myVector.begin(), myVector.end(), out_it);
}

void linearMatrix::Read_File_Matrix(const char *Path)
{
ifstream FILE(Path, std::ios::in | std::ifstream::binary);

if(!FILE)
{
cerr << "Cannot open the file" << endl;
exit(1);
}
FILE.read(reinterpret_cast<const char *>(&myWidth), sizeof(myWidth));
FILE.read(reinterpret_cast<const char *>(&myHeight), sizeof(myHeight));
istreambuf_iterator<float> iter(FILE);
copy(iter.begin(), iter.end(), std::back_inserter(myVector));
}

Проблемы:

1- ostreambuf_iterator<float> out_it (FILE);

ошибка: неверное преобразование из «void *» в
‘Std :: ostreambuf_iterator :: streambuf_type * {aka
std :: basic_streambuf> *} ’
[-Fpermissive]

2- FILE.read(reinterpret_cast<const char *>(&myWidth), sizeof(myWidth));

ошибка: неверное преобразование из «const char *» в «std :: basic_istream :: char_type * {aka char *}’ »[-fpermissive]

3- FILE.read(reinterpret_cast<const char *>(&myHeight), sizeof(myHeight));

ошибка: неверное преобразование из «const char *» в
‘Std :: basic_istream :: char_type * {aka char *}’ [-fpermissive]

4- std::ifstream FILE(Path, std::ios::in | std::ifstream::binary);

ошибка: неверное преобразование из «void *» в
‘Std :: ostreambuf_iterator :: streambuf_type * {aka
std :: basic_streambuf> *} ’
[-Fpermissive]

5-копия (iter.begin (), iter.end (), std :: back_inserter (myVector));

ошибка: в классе std :: istreambuf_iterator нет члена с именем
‘начать’

ошибка: в классе std :: istreambuf_iterator нет члена с именем
‘конец’

Что я делаю неправильно? Я использую затмение nsight из CUDA, но компилирую проект C ++ с помощью g ++. Я имею в виду: Чтение и запись std :: vector в файл правильно

#include <iostream>
#include <algorithm>
#include <iterator>
#include <fstream>
#include <vector>

using namespace std;

void Write_File_Matrix(const char *Path)
{
float myWidth = 0;
float myHeight = 0;
vector<float> v;
v[0] = 1;
v[1] = 2;
v[2] = 3;
ofstream outFILE(Path, ios::out | ofstream::binary);
outFILE.write(reinterpret_cast<const char *>(&myWidth), sizeof(float));
outFILE.write(reinterpret_cast<const char *>(&myHeight), sizeof(float));
ostreambuf_iterator<float> out_it (outFILE);
copy(V.begin(), V.end(), out_it);
}

void Read_File_Matrix(const char *Path)
{
float myWidth = 0;
float myHeight = 0;
vector<float> v;

ifstream inFILE(Path, ios::in | ifstream::binary);

if(!inFILE)
{
cerr << "Cannot open the file" << endl;
exit(1);
}
inFILE.read(reinterpret_cast<const char *>(&myWidth), sizeof(myWidth));
inFILE.read(reinterpret_cast<const char *>(&myHeight), sizeof(myHeight));
istreambuf_iterator<float> iter(inFILE);
copy(iter.begin(), iter.end(), std::back_inserter(myVector));
}

int main() {

Write_File_Matrix("M.dat");
Read_File_Matrix("R.dat");

return 0;
}

0

Решение

1- ostreambuf_iterator out_it (FILE);

ошибка: недопустимое преобразование из ‘void *’ в bu std :: ostreambuf_iterator :: streambuf_type * {aka std :: basic_streambuf> *} ’[-fpermissive]

std::ostreambuf_iterator принимает в качестве параметра шаблона тип символа потока, а НЕ тип, в который вы хотите преобразовать. Пытаться:

std::ostreambuf_iterator<char> out_it(FILE);

То же самое для № 4.


РЕДАКТИРОВАТЬДавайте решать твои большие проблемы вместо твоих маленьких:

Не беспокойтесь об итераторах, просто запишите векторные данные за один раз:

void Write_File_Matrix(const char *Path)
{
float myWidth = 0;
float myHeight = 0;
vector<float> v;
v[0] = 1;
v[1] = 2;
v[2] = 3;
ofstream outFILE(Path, ios::out | ofstream::binary);
outFILE.write(reinterpret_cast<const char *>(&myWidth), sizeof(float));
outFILE.write(reinterpret_cast<const char *>(&myHeight), sizeof(float));
outFile.write(reinterpret_cast<const char *>(&v[0]), v.size()*sizeof(float));
}

Чтение, однако, все еще должно быть поштучно.

void Read_File_Matrix(const char *Path)
{
float myWidth = 0;
float myHeight = 0;
vector<float> v;

ifstream inFILE(Path, ios::in | ifstream::binary);

if(!inFILE)
{
cerr << "Cannot open the file" << endl;
exit(1);
}
inFILE.read(reinterpret_cast<char *>(&myWidth), sizeof(myWidth));
inFILE.read(reinterpret_cast<char *>(&myHeight), sizeof(myHeight));
float f;
while( inFILE.read(reinterpret_cast<char *>(&f), sizeof(f)))
v.push_back(f);
}
4

Другие решения

РЕДАКТИРОВАТЬ: удален неправильный ответ на 1, 4.

Re: 2, 3. Вы не можете прочитать в const char*; его Const. Приведение к char* вместо. Вот что говорится в сообщении об ошибке.

Re: 5. Да, итераторы не имеют begin() а также end() функции-члены. У вас уже есть итератор для начала файла (как только предыдущие проблемы будут решены). Его имя iter, Теперь вам нужен итератор конца файла, и правильный вызов std::copy(iter, end_iter, std::back_inserter(myVector));,

4

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector