How to write integer values to a binary file?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mohammed alhadi
    New Member
    • May 2011
    • 8

    How to write integer values to a binary file?

    Hi All,

    There is an error here, can any body tell me how to do it right? (copy from text file to Binary file)

    Code:
    #include "stdio.h"
    #include  "iostream.h"
    #include "fstream.h"
    
    void main()
    {
    ifstream inFile;
    
    inFile.open("c:\\file.txt");
    
    FILE  *pBinaryFile;
    char buffer;
    //pTextFile = fopen("c:\\file.txt", "r");
    pBinaryFile = fopen("binaryfile.bin", "wb");
    
    while(! inFile.eof())
    {
    buffer= inFile.get();
    fwrite(buffer, 1, 1, pBinaryFile);
    }
    fclose(inFile);
    fclose(pBinaryFile);
    
    }
    error C2664: 'fwrite' : cannot convert parameter 1 from 'char' to 'const void *'
    Last edited by Niheel; May 12 '11, 04:57 PM.
  • mac11
    Contributor
    • Apr 2007
    • 256

    #2
    The immediate answer is that fwrite wants a pointer and you've given it a char. So give it a pointer:
    Code:
    fwrite(&buffer, 1, 1, pBinaryFile);
    Further than that though, you might run into difficulty when it comes to text to binary conversion. That is, say infile.txt has a number in it "512"

    You'll read the first byte "5", which is the ascii value of the character '5' and explicitly not the binary value of the number 5.

    You really probably want to read the string "512" and convert that to a number 512 and write that in binary form to your file.

    see http://www.parashift.com/c++-faq-lit...alization.html for a good read about text to binary conversion.

    Why are you reading a text file and outputting it in "binary"? I mean, what are you going to do with it once its in binary form?

    Comment

    • mohammed alhadi
      New Member
      • May 2011
      • 8

      #3
      Thank you for your answer, and the reason why I am using binary files is that I have a big 3D Matrix of integer numbers and I wrote its values in a text file but the access to text file is slower that binary file so I want to convert it and then access it from another program as binary file and deal with it by processing its data and copying it in to several matrices(partit ioning the data)

      Comment

      Working...