2017-05-08 1 views
-1

어떻게 바이너리 파일에서 새 문자 배열로 데이터를 올바르게 쓸 수 있습니까? 나는이 질문이 여러 번 여기에서 물어 봤지만 아직도 제대로 할 수 없다는 것을 알고있다.바이너리 파일에서 char 배열로 데이터를 올바르게 읽는 방법

내가 지금까지 ..

struct Computer_Details { 

     char computer_type[99]; 
     int release_year; 
     float price; 

    }; 


    Computer_Details pc_details; 

     cout << "Enter Computer Type: "; 
     cin.getline(pc_details.computer_type, 255); 
     cout << "Enter Computer Release Date: "; 
     cin >> pc_details.release_year; 
     cout << "Enter Computer Price: "; 
     cin >> pc_details.price; 
     cout << "\n\n"; 

     //Create File 
     ofstream file; 
     file.open("PC_Database.data", ios::binary | ios::app); 

     if (!file) cout << "Couldn't open file\n"; 
     else { 
     file.write((char*)&pc_details, sizeof(Computer_Details)); 
     file.close(); 
     } 


     ifstream readFile; 
     readFile.open("PC_Database.data", ios::binary); 
     if (!readFile) cout << "Couldn't Open File\n"; 
     else { 
     readFile.seekg(0, ios::end); 
     int fileSize = readFile.tellg(); 
     int pcCount = fileSize/sizeof(Computer_Details); 

     readFile.seekg(0, ios::beg); 
     Computer_Details *pc_details = new Computer_Details[pcCount]; 
     readFile.read((char*)pc_details, pcCount * sizeof(Computer_Details)); 

     char *buff = new char[299]; 

     for (int i = 0; i < pcCount; i++) 
     { 
      //write to buff char 
     } 
     readFile.close(); 
    } 
+0

['strcpy'] (http://en.cppreference.com/w/cpp/string/byte/strcpy)를 사용할 수 있습니다. –

+2

[C++의 char 배열로 이진 파일 읽기] 가능한 중복 (http://stackoverflow.com/questions/33935567/reading-binary-file-into-char-array-in-c) – didiz

+2

이 대답은 도움이되지 않았습니다. – Andrew

답변

0

을 시도하고이 구조의 크기로 비교 한 내용이 :

struct Computer_Details { 
     char computer_type[100]; 
     int release_year; 
     float price; 
    }; 

같은 문제는 읽기/쓰기하려는 구조체 int와 같은 다른 두 유형 사이의 변수 bool.

이 시도 :

readFile.read((char*)pc_details->computer_type, sizeof(Computer_Details::computer_type)); 
readFile.read((char*)pc_details->release_year, sizeof(Computer_Details::release_year)); 
readFile.read((char*)pc_details->price, sizeof(Computer_Details::price)); 

편집 :이 댓글의 예를 살펴 : https://stackoverflow.com/a/119128/7981164

0

아마 문제가 당신의 구조의 크기, 구조 체크 크기는

std::ifstream input(szFileName, std::ios::binary); 
data = std::vector<char>(std::istreambuf_iterator<char>(input), 
    (std::istreambuf_iterator<char>())); 
char* charArray = &data[0]; 
size_t arraySize = data.size(); 
+2

왜 그럴까요? 당신이 한 일과 그 이유를 설명하십시오. – user4581301

+0

'data' 벡터의 버퍼가 필요한 문자 배열입니다. 생성자의 인수는 두 개의 반복자입니다. 두 번째 생성자는 기본값이며'it' 반복자로 취급됩니다. – Oliort

0

내 생각 엔 당신이 어딘가에를 전송하고 데이터를 재구성 할 수 있도록 버프로 pc_details을 밀어 할 것입니다 . 이 작업을 수행 할 때

for(int i=0; i < pcCount; i++) 
{ 
    memcpy(buff, (char*)pc_details, sizeof(computer_details)); 
    buff += sizeof(computer_details); 
    pc_details++; 
} 

그러나, 당신은 정렬 염두해야하고 그에 따라 패딩을 제공 : 그런 경우

, 당신은이 작업을 수행 할 수 있습니다. 그리고 코드는 배열 범위를 검사해야합니다.

관련 문제