2016-06-07 5 views
0

에 저장하는 것은 정말 이상한 일입니다. 나는이 질문에 대한 답을 stackoverflow에서 찾지 못했습니다.<int>을

std::vector<int>을 파일로 저장하려고합니다. std::ostreambuf_iterator<char> 파일에 쓰기 전에 charv의 각 값을 변환하는 것이 여기,

std::vector<int> v{0,1,2,4,8,16,32,64,128,256,512}; 
std::ofstream outfile("test.data", std::ios::out | std::ofstream::binary); 
std::copy(v.begin(), v.end(), std::ostreambuf_iterator<char>(outfile)); 
outfile.close(); 

그러나 문제 : 다양한 장소에서 나는 다음과 같은 코드를 발견했다. 따라서 256512 값은 0으로 변경됩니다.

00000000 00 01 02 04 08 10 20 40 80 00 00 

내 생각은 std::ostreambuf_iterator<int>std::ostreambuf_iterator<char>을 변경했다, 그러나 그것은 작동하지 않습니다 결과 파일은 hexedit에 따라 다음과 같습니다. 컴파일러에서 다음 오류를 throw합니다.

error: no matching function for call to ‘std::ostreambuf_iterator<int>::ostreambuf_iterator(std::ofstream&)’ 
std::copy(v.begin(), v.end(), std::ostreambuf_iterator<int>(outfile)); 

이 문제를 해결하려면 어떻게합니까?

+0

'사용법 #include '와'사용법 #include '. 또한 아마도'#include ' – Arunmu

+0

@Arunmu 두 가지가 모두 포함됩니다. – user38034

+2

단순히 | std :: ofstream :: binary'.어쨌든 바이너리 파일을 원하지 않습니다. –

답변

1

바이너리로 직렬화 할 수 있습니다. 엔디안과 같은 문제 만 기억하면 괜찮습니다. 기본적으로 std :: ofstream 및 ifstream write() 및 read()를 사용하십시오.

두 직렬화의 progs 아래 일렬 화를 푸는 표시됩니다, 빠른 해킹, 그래서이있을 수있는 오류 :

#include <fstream> 
#include <stdexcept> 
#include <iostream> 
#include <vector> 

using std::cout; 
using std::vector; 
using std::ofstream; 
using std::ios; 

int main() 
{ 
    vector<int> datavec{0, 1, 2, 4, 8, 16, 32, 64, 128, 256, 512}; 

    ofstream outfile; 
    outfile.open ("datafile.bin", ios::out | ios::trunc | ios::binary); 

    for (auto val : datavec) { 
     outfile.write(reinterpret_cast<const char *>(&val), sizeof(int)); 
     if (outfile.bad()) { 
      throw std::runtime_error("Failed to write to outfile!"); 
     } 
    } 

    cout << "Wrote data to file. Done.\n"; 
} 
////////////////////////////////////////////////// 

#include <fstream> 
#include <stdexcept> 
#include <iostream> 
#include <vector> 

using std::cout; 
using std::vector; 
using std::ifstream; 
using std::ios; 
using std::ios_base; 

int main() 
{ 
    vector<int> datavec; 

    ifstream infile; 
    infile.open ("datafile.bin", ios::in | ios::binary); 

    while (infile) { 
     int val; 
     infile.read(reinterpret_cast<char *>(&val), sizeof(int)); 
     if (infile.bad()) { 
      throw std::runtime_error("Failed to read from infile!"); 
     } 
     if (infile.eof()) break; 
     datavec.push_back(val); 
    } 

    cout << "Read data file. Contents of datavec: \n"; 
    for (auto val : datavec) { 
     cout << val << ", "; 
    } 
    cout << "\nDone\n"; 
} 
+1

고마워, 그게 내가 원하는거야. read 값을 벡터에 보내기 전에,'if (infile.eof()) break;'브랜치를 만들어야한다. 그렇지 않으면 마지막 읽기 값이 두 번 푸시됩니다. – user38034

+0

@ user38034 좋은 지적으로 제안한 추가 라인으로 src 코드를 수정했습니다. –

1

이 아닌 std::ostream_iterator을 찾고 있습니다. 결과 출력은

std::vector<int> v{0,1,2,4,8,16,32,64,128,256,512}; 
std::ofstream outfile("test.data", std::ios::out | std::ofstream::binary); 

std::copy(v.begin(), v.end(), std::ostream_iterator<int>(outfile)); 
outfile.close(); 

참고한다 :

01248163264128256512 

이것은 단지 << 연산자를 사용하는 경우로서, 출력 스트림 int 벡터의 값을 기록하지만없이 분리기되는 수도 있고 네가 정말로 원하는 것이 아니 겠지. 그러나 그것은 그것이하는 일입니다.

+0

예. 이것이 최선의 방법입니다. "\ n", "", ","등의 구분 기호를 전달하려는 경우에도 std :: ostream_iterator ()에 두 번째 인수로 전달하면 해당 형식으로 저장됩니다. – sagar

0

스트림을 만들 때 std::ofstream::binary을 선택적으로 삭제하십시오 (ofstream의 기본값 인 std::ios::out도 삭제할 수 있음).

가장 중요한 것은 std::ostreambuf_iterator<char> 대신 std::ostream_iterator<int>을 사용하는 것입니다.

std::vector<int> v{0,1,2,4,8,16,32,64,128,256,512}; 
std::ofstream outfile("test.data"); 
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(outfile)); 
outfile.close(); 

는 또한 ostream_iterator을 만들 때 구분 기호를 추가 할 수 있습니다. 당신은 문자로 파일에 정수를 작성 찾고 있다면

0

다음 for_each 사용할 수 있습니다

std::for_each(v.begin(), v.end(), [&outfile](int x){outfile << x;}); 

이 그들 사이에 공백과 한 줄에 파일에 문자열로 정수를 쓸 것입니다, 예 :

01248163264128256512

관련 문제