Write output to binary file in C/C++?

How can I write output to a file in binary format instead of ascii?
Or... if I am using a buffer.. to write a buffer to binary format instead of ascii?
I am writing a lot of data to a text file and I would like to reduce the size by writing it all into a binary file instead of ascii?
Last edited by kdar (2012-12-13 14:36:41)

Basic I/O?
char buffer[100];
// C++ style
ofstream file;
file.open ("data.bin", ios::out | ios::binary);
file.write(buffer, sizeof buffer);
/* C style */
FILE* file2 = fopen("data2.bin", "wb");
fwrite(buffer, sizeof buffer, 1, file2);
A lot of people prefer the old C style functions for binary i/o even in C++ (and iostream for formatted i/o). Writing and readong more complex structures requires some castin, in C++ usually done with reinterpret_cast<char*>(someStructure).

Similar Messages

  • Can TestStand open, read, write and close binary files?

    From a TestStand sequence, I need to open, read, write and close binary files. Does TestStand support this capability?

    Christine -
    In the past I have used the C/C++ Adapter to call directly into the CVI RTE functions. The CVI functions I have used are OpenFile, WriteFile and CloseFile. The functions are exported from the DLL as CVI_OpenFile, CVI_WriteFile, and CVI_CloseFile. I just had to make sure that on termination of the sequence, that the integer handle was properly released by calling the close function.
    If you are using LabVIEW, you could call directly into the low level VIs to do a similar set of operations.
    Scott Richardson (NI)
    Scott Richardson
    National Instruments

  • What is the best combination of read and write objects to binary files ...

    Hi everyone,
    what are the best combination of read and write objects to read/write a record of customers from a binary file. I should be able to use StringTokenizer. I am bit confused with all these Stream reader and writers.
    abdul

    You are, indeed, confused:
    o StreamTokenizer works on character input, not binary input.
    o Readers and Writers in general work on character streams, not binary.
    That leaves you various input streams and output streams for reading binary data.

  • Write structure to binary file and append

    I have a very simple problem that I cannot seem to figure out, which I guess doesn't make it so simple, for me at least.  I've made a little example .vi which basically breaks down what I want to to.  I have a structure, in this instance 34 bytes of various data types.  I would like to iteratively write this structure to a binary file as the data in the ACTUAL structure in my .vi will be changing through time.  I'm having trouble getting the data to be appended to the binary file rather than overwriting it since the file size is always 34 bytes regardless of how many times I run the .vi or run the for loop.
    I'm not an expert, but it seems if I write a 34 byte structure to a file 10 times, the final product should be a binary file of 340 bytes (assuming I haven't padded or prepended with size).
    One really strange thing is that I keep getting error #1544 when I wire the refnum out wire to the file dialog input on the write function, but it works fine when I wire the file path directly to the write function.
    Can someone please swoop in and save me from this remedial task?
    Thanks for all the help. NI Forum rules!
    Solved!
    Go to Solution.
    Attachments:
    struct_to_bin.vi ‏13 KB

    Did you consider reading the text of the error message? Don't set the "disable buffering" input to true - just leave that input unwired. Why do you want to disable buffering?
    As a general practice, the file refnum should be stored in a shift register around the for loop instead of using loop tunnels, that way if you have zero iterations you will still get the file refnum passed through correctly. Also, there is no need for Set File Position inside the loop, since the file location is always the end of the last write unless it's specifically moved to another location. You might want it once outside the loop after you open the file, if you're appending to an existing file.

  • How to read and write in a binary file?

    Hi all,
    how can i search in a binary file for string and replace this string with another
    bin file ...test.bin
    search String "DE AD FA 01"
    regards
    gebi

    You need to install Google on your computer. That way, you can search for all the information on that algorithm available on the Internet.

  • Can FileReader write to a binary file

    I am just wondering because i would like to use it for a program that is suppose to write in binary. If it can, should I just insert an array of characters that are 1 or 0 or should i actually figure out the bites involved.

    Readers read, not write.
    So you have a char[] that looks like this: {'0','1','0','0',...}? That's an odd thing to have. I would roll up my sleeves and convert it to a byte[]. Writing that to a file is a simple matter: use FileOutputStream.
    edit: can you avoid having a char[] in the first place?

  • Need to write output to a file in pipe ( | )delimited format

    Hi All,
    I am trying to extract values from a database and write them to a text file with pipe( | ) delimited format. Can someone guide me on this with an example. I ma very much new to Java.
    Thanks for help,
    Abhi

    abhibora wrote:
    Hi All,
    I am trying to extract values from a database and write them to a text file with pipe( | ) delimited format. Can someone guide me on this with an example. I ma very much new to Java.
    Thanks for help,
    AbhiSimply print your values separated by the '|' pipe symbol; I don't see the problem.
    kind regards,
    Jos

  • Trying to write out a binary file

    I have found that using the Dataoutputstream is the way to read the file but writing I can't seem to get. Below is the code. It is writing out some data but not all is accurate is there anyother way to copy exactly what is in one file to another by just renaming??
    DataInputStream brL = new DataInputStream(new FileInputStream(LogFile));
              DataInputStream brE = new DataInputStream(new FileInputStream(ECGFile));
              DataInputStream brS = new DataInputStream(new FileInputStream(SpeechFile));
              DataInputStream brH = new DataInputStream(new FileInputStream(HistoryFile));
    DataOutputStream bwL = new DataOutputStream(new FileOutputStream("c:\\Projects\\FirstSupport\\LOG_data.out"));
              DataOutputStream bwE = new DataOutputStream(new FileOutputStream("c:\\Projects\\FirstSupport\\ECG_data.out"));
              DataOutputStream bwS = new DataOutputStream(new FileOutputStream("c:\\Projects\\FirstSupport\\SPEECH_data.out"));
              DataOutputStream bwH = new DataOutputStream(new FileOutputStream("c:\\Projects\\FirstSupport\\HISTORY_data.out"));
              System.out.println("Starting to copy files");
              try{
              int c = -1;
              while((c = brL.read()) != -1){
                   bwL.write(c);
              while((c = brE.read()) != -1){
                   bwE.write(c);
              while((c = brS.read()) != -1){
                   bwS.write(c);
              while((c = brL.read()) != -1){
                   bwH.write(c);
         }

    use a FileInputStream and a FileOutputStream. You don't need to use the DataInput and OutputStreams. You can use a byte array to store the contents of the file and then write the contents of the byte array to a file.
    try{
        FileInputStream f = new FileInputStream("myFile.dat");
        byte[] contents = new byte[f.available()];
        f.read(contents);
        FileOutputStream o = new FileOutputStream("myFile.new");
        o.write(contents);
        f.close();
        o.close();
    catch(IOException ioe){
        ioe.printStackTrace();

  • Write to binary file different from 8.0 to 8.2?

    I am communicating with a device via USB and am using a method setup by the USB driver programmer. To communicate, I write to a binary file with a filename of \\?\COMx. This has been working fine for about a  year in mfg with Labview 8.0. I recently "upgraded" to 8.2 and now it does not work. If I save for a previous version and run 8.0 it works fine. How can I make this work with 8.2?

    Yi Y,
    The USB device is one of the instruments we manufacture. The USB driver is written so writing to the USB port is just like writing to a file. I use the binary read/write VI's to send and receive commands to this USB device. The filename I use is \\?\COM#. I am told by the USB driver creator that this is common for low level C. I have been using this VI for that last year and recently upgraged from 8.0 to 8.2 and it does not work. I run the same vi under 8.0 and it works fine. This is not a common way to communicate, so will probably not get an answer.
    My next question is, is there any way to run an 8.0 dll or vi from an 8.2 executable?
    Thanks
    Hi dgtest1,
    Which USB device you are using, and which driver are you using? I'm trying to figure out specifically how you are communicating with the USB device by writing a binary file and how was the binary file written.  Could you please post more information to describe in more details about what your set up is doing?
    Thanks!
    Yi Y.
    Applications Engineer
    National Instruments
    http://www.ni.com/support

  • Writing binary files & trouble with no unsigned byte type

    I've got a fair amount of Java experience, enough to know what I'm doing most of the time but I do have a vast experience with C & C++ which helps my Java. I've stumbled across a problem when trying to write out files in binary.
    If I was to write out a binary file, I would always choose C/C++ to do this because simply because I'm at ease with the implementation.
    I've now written a Java program which needs to output a file in binary and I'm having real issues doing the most simple things because of no unsigned support.
    I want to write out elements byte-by-byte and make use of the 8-bits provided in the byte type in Java.
    Let's assume I've done my processing and I end up with an int. I know that this int is 0-255 in value. I now want to pack it into a byte and write it to my file. How do I go about assigning the byte without Java 'converting' it to a signed byte? I simply want to copy the lower 8-bits of the int and duplicate them into the byte variable - no conversion.
    In C you would do something like this:
    char mySignedChar = *( (char*)&(unsigned char)myInt ) );
    What's the Java equivalent? Am I going about this the right way?

    Whether a byte is signed or unsigned only matters if one is doing arithmetic on it. If the int is 0-255 then you just cast to a byte using
    byte theByte = (byte)theIntValue;When reading back you just use
    int theByteAsAnInt = theByte & 0xff;

  • How can I append an output to a file that is simultaneo​usly being created

    i have an output that lets me know at the end of a test how many cycles the motor drive has run, i also have a file being created with my stress vs time data. I was wondering why I cant get the cycle output to append to the end of the data file after the test has been completed.  I am using labview 8.0. the data file is created using an express vi that i converted to a sub vi so that i could wire a description to it.  I have little clue of what I have here because i was asked with my limmited knowledge to figure out what someone else slapped together.  any help would be greatly appreciated!

    I created a vi for you that does the following...
    reads two types of data to cluster (data, time)
    writes data to binary file (smaller than txt, or spreadsheet)
    once stopped, the program will append the number of data messages to the end of the file
    I also showed two ways of reading the data back...
    reading the data first, then the number of messages
    or reading the number of messages, using that number to read the all the data left in the file
    Hopefully this is what you were looking for.
    Attachments:
    write data to file.vi ‏45 KB

  • WLS 5.1 w/sp8 garbeling binary files when uploaded.

    I have implemented multiple methods of handling file uploads in servlets.
              I have tried the Marsh:
              http://sourceforge.net/projects/marsh/
              and the Oreilly com.oreilly.servlet:
              http://www.servlets.com/cos/index.html
              helper libraries as well as my own code, yet I still have the same problems.
              For some reason some bytes in binary files are being converted to ascii '?'s
              instead of the proper bytes. All uploaded files from all three
              implementations contain the same error, yet no bugs are listed in any of
              them (even Weblogic.)
              I am running WLS 5.1 SP8 on Windows and Linux and am having the same errors
              on both. If you might be thinking it's the way I'm writing the file then
              here is how I am outputing (once I get an input stream from the
              HttpServletRequest).
              /* Code snippet */
              x = myinput_stream.read();
              while(x >= 0) {
              myfile_writer.write(x);
              x = myinput_stream.read();
              myfile_writer.close();
              /* End code snippet */
              If you know how to fix this or you have gotten WLS to upload binary files at
              all then please reply and let me know.
              

    I'll try that and then let you know....
              "Dimitri Rakitine" <[email protected]> wrote in message
              news:[email protected]...
              > Writer's are for character streams - it will work if you use OutputStream
              > to write to a binary file.
              >
              > Hoopy Hacker <[email protected]> wrote:
              > > I have implemented multiple methods of handling file uploads in
              servlets.
              >
              > > I have tried the Marsh:
              >
              > > http://sourceforge.net/projects/marsh/
              >
              > > and the Oreilly com.oreilly.servlet:
              >
              > > http://www.servlets.com/cos/index.html
              >
              > > helper libraries as well as my own code, yet I still have the same
              problems.
              > > For some reason some bytes in binary files are being converted to ascii
              '?'s
              > > instead of the proper bytes. All uploaded files from all three
              > > implementations contain the same error, yet no bugs are listed in any of
              > > them (even Weblogic.)
              >
              > > I am running WLS 5.1 SP8 on Windows and Linux and am having the same
              errors
              > > on both. If you might be thinking it's the way I'm writing the file
              then
              > > here is how I am outputing (once I get an input stream from the
              > > HttpServletRequest).
              >
              > > /* Code snippet */
              > > x = myinput_stream.read();
              > > while(x >= 0) {
              > > myfile_writer.write(x);
              > > x = myinput_stream.read();
              > > }
              > > myfile_writer.close();
              > > /* End code snippet */
              >
              > > If you know how to fix this or you have gotten WLS to upload binary
              files at
              > > all then please reply and let me know.
              >
              > --
              > Dimitri
              

  • Read a binary file written by a C program

    Hi,
    I have a binary file that is written by a C program. The C program fills the values into a structure and then writes to the binary file. I posted a message earlier requesting for help in reading this data and got the help. I am able to read the various fields.
    The question is in the link below.( Just in case of reference)
    http://forum.java.sun.com/thread.jsp?forum=31&thread=509414
    My question is the structure totally has 32456 bytes. It is kind of very difficult to get the values that I require as it is scattered. Moreover, the structure is nested. Based on a count in the first structre I have to loop that many times the second structre and retrive a particular value each time.
    For example : I have this
    typedef struct {
    int a;
    char b[10];
    int c;
    } one;
    typedef struct {
    long d;
    char e[9];
    char f[8];
    }two;
    typedef struct {
    one first;
    two second[10];
    }main;
    So, here first i will have to get the int c from struct one and based on that value i will have to loop the struct two. The maximum value can be 10 which is given in struct main.
    So, if i use DataInputStream, ByteBuffer and get the values based on buffer.getInt(), etc the process is very tedious and i tend to make error in counting the bytes to get the values as such. Moreover as I have said, the byte array is very large.
    Is there any other simple way to do this. I dont need to write to the file. I will just need to read from the file based on the C header. Do, I need to use JNI for this, in that case any pointers would be very much useful as I am very far from those topics.
    Thanks,
    Sreeni.

    So, what is the possible solution for this. I am badly
    needing this to complete my project.
    The solution has been provided to you. The only alternative would be to read the file using JNI and populate and create Java objects using the native interface. This would most likely be more difficult than just doing it using byte counting.
    I'm certain that a creating person could create a bunch of method calls that could encapsulate each structure used here. Doing this byte by byte is really a trivial exercise - you could have it finished and working in less than an hour if you put your mind to it.
    - K

  • Writing binary file - random places

    Hi,
    I want to write to random places inside a binary file using powershell.
    something like a function write(position,value) 
    Original file content "0123456789"
    write(1,2) -> file is now "0223456789"
    write(6,2) -> file is now "0223452789"
    write(end,12345) -> file is now "022345278912345"
    Is something like this possible? And how? Does somebody have any linkes for me to follow.
    With kind regards,
    Maurice Lucas

    The example is text.  You cannot write to a binary file using text.
    We would open the file as a binary stream and use file seek methods.
    A binary file has only 1s and 0s.  They may look like hex in a binary editor.
    See:
    http://msdn.microsoft.com/en-us/library/d3wke8tz(v=vs.110).aspx
    Binary is written to by byte position and buffer length.
    ¯\_(ツ)_/¯

  • Bug in LV8 : 'Save for previous version' and 'Write to Binary File' VI

    Hello
    I am using LabVIEW 8's revamped 'Write to Binary File' VI with a 'TRUE' boolean constant wired to the optional 'prepend array or string size?' to write non-trivial structures to a binary file. I then read the file with the 'Read from Binary File' VI and everything is fine. I don't wire anything to the 'file (use dialog)' input (don't know if this can help).
    However, after saving my VI for LabVIEW 7.1, I cannot read the binary files created with the LV7 version of the VI anymore. After examining the LV7 converted version of the VI, there is a 'FALSE' boolean constant that is wired to the equivalent of the 'prepend array or string size' input, which breaks the binary format that is expected.
    The attached files are LV8 and 'saved for LV7' versions of a dummy VI that writes an array of 5 integers into a binary file. To test the bug, start LV8, open the LV8 version, run it and create a 'test-lv8.bin' file, then open the LV7 version, run it and create a 'test-lv7.bin' file. Check the content of the two files : the size of the array is indeed missing from the 'test-lv7.bin' file, which can be assimilated as a bug in my opinion.
    I think I found another one too : if in LV8 I wire the 'cancelled' boolean output of the 'Open/Create/Replace file' to the selector of a case structure, the 'converted to LV7' version VI will have an error, saying the Case Structure selector is not wired.
    Could someone please confirm these are indeed bugs ?
    Thanks in advance and have a nice day.
    Eric Batut
    Attachments:
    Test Binary File v7-v8 LV7.vi ‏15 KB
    Test Binary File v7-v8 LV8.vi ‏7 KB

    I'm using LV8.6 and need to read a .bin file created in MATLAB. This file obviously does not contain the 4 byte header that LabVIEW prepends .bin files with. So when I use Read from Binary File, I get no data (I'm trying to read an array of doubles). I've tried making my .bin file both in native and big-endian format and changing the representation (double, int64, float64) but none of this works. I noted that if I create the same array in a .bin file in LabVIEW and wire a FALSE to the "prepend array or string size?", my VI for reading .bin files can't read this file either.
    Any work-arounds here?
    (I'll try attaching my write & read VI's)
    Attachments:
    ReadWriteBinFile.zip ‏19 KB

Maybe you are looking for

  • How to see lyrics for song playing?

    I've got lyrics entered in most of the songs in my iTunes library. I notice that on my iPad 1, when I play a song on the iPod app, I see the cover image but no lyrics. A found a web page that said I'd see the lyrics if I tapped the cover image, but t

  • 2 ipods. 2 Users. 1 itunes

    I have an iPhone and my sister has and iPod, but we only have 1 iTunes because we only have 1 computer. We both have different music but it's all in the same library and we've been seperating it by playlists. However, it's getting annoying because we

  • Cant burn a cd thru tunes

    cant burn a cd thru Itunes I have reinstaled the latest Itunes and nothing please help

  • Binary file to variable

    Hi, I want to store a binary file content (it is a MS WORD file) onto a java variable (type String ?) to use this variable to create a new file identical by writing this variable value into a new file. I tried it as follow : 1- I read a file using a

  • Displaying images through forms6 stored as bfile

    The image is stored in a database as bfile datatype. How the image can be displayed using forms6?