Answer the question
In order to leave comments, you need to log in
Writing a vector to a binary file, in a loop - C++?
There is an
input.txt file with the following content:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
25 26 27 28 29 30
.dat is only element-wise with the line index. The file must have the structure: index (4 bytes) + 6 values from a vector of 2 bytes.
01 00 00 00 01 00 02 00 03 00 04 00 05 00 06 00 02 00 00 00 07 00 08 00 etc.
Here is my code but it is wrong
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
using namespace std;
int main()
{
std::fstream input("input.txt");
std::vector<short> vec; // значения из файла
std::copy(std::istream_iterator<int>(input), std::istream_iterator<int>(), std::back_inserter(vec));
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
ofstream fout("data.dat", std::ios::out | ios::binary);
int countstring = 5;
int index = 0;
int row = 6;
for (int i = 0; i <= countstring; i++) {
index = i + 1;
fout.write((char *)&index, sizeof index);
for (size_t j = 0; j < row; ++j)
{
fout.write((char*)&vec[i * 6], row * sizeof(short));
}
}
fout.close();
return 0;
Answer the question
In order to leave comments, you need to log in
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
std::fstream input("input.txt");
std::vector<short> vec; // значения из файла
std::copy(std::istream_iterator<int>(input), std::istream_iterator<int>(), std::back_inserter(vec));
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
std::ofstream fout("data.dat", std::ios::out | std::ios::binary);
const size_t columnCount = 6;
for (size_t i = 0; i < vec.size(); i+= columnCount)
{
int index = i / columnCount + 1;
fout.write((char *)&index, sizeof(int));
for (size_t j = 0; j < columnCount; j++)
{
fout.write((char*)&vec[i + j], sizeof(short));
}
}
fout.close();
return 0;
}
index (4 bytes) + 6 values from vector of 2 bytes
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question