정수 값을 파일에 쓰고, 쓰여진 순서대로 정수를 읽고 표시하는 간단한 프로그램을 작성하려고합니다. 파일에 기록 된 정수는 {0,2, .... 18}입니다. 다음은 코드입니다.C++에서 이진 파일 읽기/쓰기
// Example program
#include <iostream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <fstream>
using namespace std;
int main()
{
typedef unsigned int uint32_t;
// Write to file
std::ofstream osObj;
string filename = "testFile";
osObj.open(filename.c_str(), std::ofstream::binary);
for (uint32_t i=0; i<10; ++i)
{
uint32_t a = i*2;
osObj.write(reinterpret_cast<const char *>(&a), sizeof(a));
//osObj.write((char *)(&a), sizeof(a));
}
//read from file
std::ifstream isObj;
isObj.open(filename.c_str(), std::ofstream::binary);
if (isObj.fail()) { cout<<"Failed to open file"<<endl; }
for (uint32_t i=0; i<10; ++i)
{
char val[sizeof(uint32_t)];
isObj.read(val, sizeof(val));
uint32_t* valUint = reinterpret_cast<uint32_t *>(val);
cout<<*(valUint)<<endl;
}
return 0;
}
예상되는 결과가 나오지 않습니다. 다음 출력을 얻고 있습니다 :
62586880
62586880
62586880
62586880
62586880
62586880
62586880
62586880
62586880
62586880
바이트 순서는 리틀 엔디안입니다. 내가 뭘 놓치고 있니?
당신이 무엇을 기대하고 무엇을 얻고 있는지에 대한 설명이 없습니다. – Slava
@Slava가 질문을 편집했습니다. – Naveen
읽기 루프는 쓰기 루프와 모양이 같을 수 있으며 'uint32_t a; osObj.read (reinterpret_cast (& a), sizeof (a)); cout << a << endl; –
NathanOliver