write a binary file?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • cylin

    #1

    write a binary file?

    Dear all,

    I open a binary file and want to write 0x00040700 to this file.
    how can I set write buffer?
    ---------------------------------------------------
    typedef unsigned char UCHAR;
    int iFD=open(szFile Name,O_CREAT|O_ BINARY|O_TRUNC| O_WRONLY,S_IREA D|S_IWRITE);
    UCHAR buffer[5]; //???????????
    write(iFD,buffe r,5);
    ---------------------------------------------------

    Thanks.

    Regards,
    cylin.


  • Richard Bos

    #2
    Re: write a binary file?

    "cylin" <cylin@avant.co m.tw> wrote:
    [color=blue]
    > I open a binary file and want to write 0x00040700 to this file.
    > how can I set write buffer?[/color]

    Not like this, in ISO C. What you've got is system-specific, either
    POSIX or not-quite-POSIX-M$.
    [color=blue]
    > typedef unsigned char UCHAR;[/color]

    Yeugh.
    [color=blue]
    > int iFD=open(szFile Name,O_CREAT|O_ BINARY|O_TRUNC| O_WRONLY,S_IREA D|S_IWRITE);[/color]

    Hungarian notation. Double yeugh. HN used to declare what everybody
    reading your code, including the compiler, already knows: the types of
    your identifiers. Triple yeugh, and go to the self-confidence shop and
    buy some.
    [color=blue]
    > UCHAR buffer[5]; //???????????[/color]

    Mixing declarations and executable statements is legal in C99 and C++,
    but not in C89. Beware the snark.
    [color=blue]
    > write(iFD,buffe r,5);[/color]

    No idea how to solve this using your low-level, unlikely-to-port
    functions. In _real_ C, you'd do something like this:

    #include <stdio.h>

    unsigned char buf[5];
    FILE *outfile;

    if (!(outfile=fope n(filename, "wb")) {
    puts("This is the place where you'd handle a file open error.");
    } else {
    if (fwrite(buf, sizeof *buf, sizeof buf/sizeof *buf, outfile) !=
    sizeof buf/sizeof *buf) {
    puts("Handle a write error here.");
    }
    /* Or, since you know that buf is an unsigned char array and
    therefore sizeof *buf must be 1:
    fwrite(buffer, 1, sizeof buf, outfile);
    */
    fclose(outfile) ;
    /* For critical applications, you should even check the return value
    of fclose(), but I rarely do this. */
    }

    Issa dat si'ple.

    Richard

    Comment

    • Irrwahn Grausewitz

      #3
      Re: write a binary file?

      "cylin" <cylin@avant.co m.tw> wrote:[color=blue]
      >
      >I open a binary file and want to write 0x00040700 to this file.
      >how can I set write buffer?[/color]

      Do you want to
      [1] write bytes in exactly the order you gave above (portable
      result), or
      [2] write an unsigned long value to the file (non-portable
      result)?
      [color=blue]
      >---------------------------------------------------
      >typedef unsigned char UCHAR;
      >int iFD=open(szFile Name,O_CREAT|O_ BINARY|O_TRUNC| O_WRONLY,S_IREA D|S_IWRITE);
      >UCHAR buffer[5]; //???????????
      >write(iFD,buff er,5);
      >---------------------------------------------------[/color]

      Neither open nor write are standard C functions.
      What you want is something like:

      #include <stdio.h>
      #include <stdlib.h>

      int main( void )
      {
      unsigned char buf[] = { 0x00, 0x04, 0x07, 0x00 };
      unsigned long ul = 0x00040700UL;
      FILE *fp;

      if ( ( fp = fopen( "foo", "wb" ) ) != NULL )
      {
      fwrite( buf, sizeof buf, 1, fp ); /* [1] */
      fwrite( &ul, sizeof ul, 1, fp ); /* [2] */
      fclose( fp );
      return EXIT_SUCCESS;
      }
      return EXIT_FAILURE;
      }

      HTH
      Regards
      --
      Irrwahn Grausewitz (irrwahn33@free net.de)
      welcome to clc: http://www.ungerhu.com/jxh/clc.welcome.txt
      clc faq-list : http://www.faqs.org/faqs/C-faq/faq/
      clc OT guide : http://benpfaff.org/writings/clc/off-topic.html

      Comment

      • Martin Dickopp

        #4
        Re: write a binary file?

        "cylin" <cylin@avant.co m.tw> writes:
        [color=blue]
        > Dear all,
        >
        > I open a binary file and want to write 0x00040700 to this file.
        > how can I set write buffer?[/color]

        Use shifts and mask operations (bitwise AND) to extract the individual
        bytes. The details depend on the byte order in which you want to write
        to the file.
        [color=blue]
        > ---------------------------------------------------
        > typedef unsigned char UCHAR;
        > int iFD=open(szFile Name,O_CREAT|O_ BINARY|O_TRUNC| O_WRONLY,S_IREA D|S_IWRITE);[/color]

        No such function in standard C. Use `fopen'.
        [color=blue]
        > UCHAR buffer[5]; //???????????
        > write(iFD,buffe r,5);[/color]

        No such function in standard C. Use `fwrite'.
        [color=blue]
        > ---------------------------------------------------[/color]

        This program should give you same hints:


        #include <stdlib.h>
        #include <stdio.h>

        int main (void)
        {
        const unsigned long value = 0x00040700;
        unsigned char buffer [4];
        FILE *f;

        /* This as known as "big-endian" byte order. */
        buffer [0] = value >> 24;
        buffer [1] = (value >> 16) & 0xFF;
        buffer [2] = (value >> 8) & 0xFF;
        buffer [3] = value & 0xFF;

        f = fopen ("testfile", "wb");
        if (f != NULL)
        {
        if (fwrite (buffer, sizeof *buffer, sizeof buffer, f) < sizeof buffer
        || fclose (f) == EOF)
        {
        fputs ("Error writing to testfile.\n", stderr);
        return EXIT_FAILURE;
        }
        }
        else
        {
        fputs ("Cannot open testfile for writing.\n", stderr);
        return EXIT_FAILURE;
        }

        return 0;
        }


        Martin


        --
        ,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
        / ,- ) http://www.zero-based.org/ ((_/)o o(\_))
        \ `-' `-'(. .)`-'
        `-. Debian, a variant of the GNU operating system. \_/

        Comment

        • Martin Dickopp

          #5
          Re: write a binary file?

          rlb@hoekstra-uitgeverij.nl (Richard Bos) writes:
          [color=blue]
          > if (fwrite(buf, sizeof *buf, sizeof buf/sizeof *buf, outfile) !=
          > sizeof buf/sizeof *buf) {
          > puts("Handle a write error here.");
          > }
          > fclose(outfile) ;
          > /* For critical applications, you should even check the return value
          > of fclose(), but I rarely do this. */[/color]

          Why do you check the return value of `fwrite' then? Most operating
          systems don't write immediately to the underlying device when `fwrite'
          is called, but have some buffering mechanism. Therefore, an error is
          far more likely to show up in `fclose' than in `fwrite' on such systems.

          Martin


          --
          ,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
          / ,- ) http://www.zero-based.org/ ((_/)o o(\_))
          \ `-' `-'(. .)`-'
          `-. Debian, a variant of the GNU operating system. \_/

          Comment

          • Martin Dickopp

            #6
            Re: write a binary file?

            Martin Dickopp <expires-2004-05-31@zero-based.org> writes:
            [color=blue]
            > if (fwrite (buffer, sizeof *buffer, sizeof buffer, f) < sizeof buffer[/color]

            That's inconsistent. Make that:

            if (fwrite (buffer, 1, sizeof buffer, f) < sizeof buffer

            Martin


            --
            ,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
            / ,- ) http://www.zero-based.org/ ((_/)o o(\_))
            \ `-' `-'(. .)`-'
            `-. Debian, a variant of the GNU operating system. \_/

            Comment

            • cylin

              #7
              Re: write a binary file? (Can't low-level I/O functions do this case?)

              Great. Thank all.

              I use low-level I/O functions because I want to the speed faster than
              stardard I/O functions.
              Can't low-level I/O functions do this case?

              Regards,
              cylin.


              Comment

              • Martin Dickopp

                #8
                Re: write a binary file? (Can't low-level I/O functions do thiscase?)

                "cylin" <cylin@avant.co m.tw> writes:
                [color=blue]
                > I use low-level I/O functions because I want to the speed faster than
                > stardard I/O functions.
                > Can't low-level I/O functions do this case?[/color]

                They can, but they're off-topic in comp.lang.c, which is only about
                standard C.

                <OT>
                They are also harder to use correctly. Note, e.g., that it is not
                necessarily an indication of error if the POSIX function `write' writes
                less bytes than requested.
                </OT>

                Martin


                --
                ,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
                / ,- ) http://www.zero-based.org/ ((_/)o o(\_))
                \ `-' `-'(. .)`-'
                `-. Debian, a variant of the GNU operating system. \_/

                Comment

                • Joona I Palaste

                  #9
                  Re: write a binary file? (Can't low-level I/O functions do this case?)

                  cylin <cylin@avant.co m.tw> scribbled the following:[color=blue]
                  > Great. Thank all.[/color]
                  [color=blue]
                  > I use low-level I/O functions because I want to the speed faster than
                  > stardard I/O functions.
                  > Can't low-level I/O functions do this case?[/color]

                  First of all, your "low-level I/O functions" might not even be available
                  on all platforms. Second of all, there is no guarantee they will be any
                  faster than standard I/O functions. They could even be slower.

                  --
                  /-- Joona Palaste (palaste@cc.hel sinki.fi) ------------- Finland --------\
                  \-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
                  "C++ looks like line noise."
                  - Fred L. Baube III

                  Comment

                  • CBFalconer

                    #10
                    Re: write a binary file?

                    Martin Dickopp wrote:[color=blue]
                    > "cylin" <cylin@avant.co m.tw> writes:
                    >[color=green]
                    >> I open a binary file and want to write 0x00040700 to this file.
                    >> how can I set write buffer?[/color]
                    >
                    > Use shifts and mask operations (bitwise AND) to extract the
                    > individual bytes. The details depend on the byte order in which
                    > you want to write to the file.
                    >[/color]
                    .... snip ...[color=blue]
                    >
                    > This program should give you same hints:
                    >
                    > #include <stdlib.h>
                    > #include <stdio.h>
                    >
                    > int main (void)
                    > {
                    > const unsigned long value = 0x00040700;
                    > unsigned char buffer [4];
                    > FILE *f;
                    >
                    > /* This as known as "big-endian" byte order. */
                    > buffer [0] = value >> 24;
                    > buffer [1] = (value >> 16) & 0xFF;
                    > buffer [2] = (value >> 8) & 0xFF;
                    > buffer [3] = value & 0xFF;
                    >
                    > f = fopen ("testfile", "wb");
                    > if (f != NULL)
                    > {
                    > if (fwrite (buffer, sizeof *buffer, sizeof buffer, f) < sizeof buffer
                    > || fclose (f) == EOF)
                    > {
                    > fputs ("Error writing to testfile.\n", stderr);
                    > return EXIT_FAILURE;
                    > }
                    > }
                    > else
                    > {
                    > fputs ("Cannot open testfile for writing.\n", stderr);
                    > return EXIT_FAILURE;
                    > }
                    >
                    > return 0;
                    > }[/color]

                    There is nothing wrong with your code above, and it illustrates
                    most things admirably, I suggest that the use of embedded tests
                    will facilitate a clearer order of things. This is a style
                    question, not a flame, and just a suggestion. My version follows:

                    #include <stdlib.h>
                    #include <stdio.h>

                    int main (void)
                    {
                    const unsigned long value = 0x00040700;
                    unsigned char buffer [4];
                    FILE *f;

                    /* This as known as "big-endian" byte order. */
                    buffer [0] = value >> 24;
                    buffer [1] = (value >> 16) & 0xFF;
                    buffer [2] = (value >> 8) & 0xFF;
                    buffer [3] = value & 0xFF;

                    if (!(f = fopen("testfile ", "wb"))) {
                    fputs("Cannot open testfile for writing.\n", stderr);
                    }
                    else if ((fwrite(buffer , sizeof *buffer, sizeof buffer, f)
                    < sizeof buffer)
                    || (EOF == fclose(f))) {
                    fputs("Error writing to testfile.\n", stderr);
                    }
                    else {
                    return 0;
                    }
                    return EXIT_FAILURE;
                    }

                    although the neophyte is still going to have trouble comprehending
                    the combined fwrite/fclose failure test. I have also added the
                    odd extraneous parentheses to make the meanings explicit.

                    This now follows the pattern "if phasefails exit else nextphase".

                    --
                    Some useful references:
                    <http://www.ungerhu.com/jxh/clc.welcome.txt >
                    <http://www.eskimo.com/~scs/C-faq/top.html>
                    <http://benpfaff.org/writings/clc/off-topic.html>
                    <http://anubis.dkuug.dk/jtc1/sc22/wg14/www/docs/n869/> (C99)


                    Comment

                    • Dan Pop

                      #11
                      Re: write a binary file?

                      In <40837a61.17265 20523@news.indi vidual.net> rlb@hoekstra-uitgeverij.nl (Richard Bos) writes:
                      [color=blue]
                      > fclose(outfile) ;
                      > /* For critical applications, you should even check the return value
                      > of fclose(), but I rarely do this. */[/color]

                      Bad idea: most of the things that can go wrong (after fopen succeeded)
                      happen at fclose time.

                      To optimise the error checking, when I generate an output file in a
                      compact succession of operations, I only check fclose and a fflush call
                      immediately preceding it (which is probably redundant).

                      OTOH, long running programs that generate output constantly (e.g. one
                      printf call per main loop iteration) should check each output call,
                      even if it's on stdout (that gets redirected to a file when the program
                      is run in non-interactive mode). No point in continuing the execution
                      if the program can no longer generate output.

                      Dan
                      --
                      Dan Pop
                      DESY Zeuthen, RZ group
                      Email: Dan.Pop@ifh.de

                      Comment

                      • Dan Pop

                        #12
                        Re: write a binary file? (Can't low-level I/O functions do this case?)

                        In <c600ft$6bclo$1 @ID-230325.news.uni-berlin.de> "cylin" <cylin@avant.co m.tw> writes:
                        [color=blue]
                        >I use low-level I/O functions because I want to the speed faster than
                        >stardard I/O functions.[/color]

                        Where did you get this silly idea from? The low-level I/O functions have
                        a relatively high cost and the stardard I/O functions are designed to
                        minimise the number of low-level I/O function calls, by doing some local
                        buffering.

                        As a result of this, it is trivially easy for the ignorant to slow down
                        his I/O by one order of magnitude, while an expert can only speed up his
                        I/O by a small percentage, by using the low-level functions instead of the
                        standard ones and removing one level of buffering, when and where it is
                        not necessary.
                        [color=blue]
                        >Can't low-level I/O functions do this case?[/color]

                        Why bother?

                        Dan
                        --
                        Dan Pop
                        DESY Zeuthen, RZ group
                        Email: Dan.Pop@ifh.de

                        Comment

                        • kal

                          #13
                          Re: write a binary file?

                          > Use shifts and mask operations (bitwise AND) to extract the individual[color=blue]
                          > bytes. The details depend on the byte order in which you want to write
                          > to the file.[/color]

                          IMHO one is better off using "htnl()." This will work fine so long as
                          all you are writing are 32 bit values.

                          Comment

                          • Christopher Benson-Manica

                            #14
                            Re: write a binary file?

                            kal <k_amir7@yahoo. com> spoke thus:
                            [color=blue]
                            > IMHO one is better off using "htnl()." This will work fine so long as
                            > all you are writing are 32 bit values.[/color]

                            I suspect you meant htonl().

                            --
                            Christopher Benson-Manica | I *should* know what I'm talking about - if I
                            ataru(at)cybers pace.org | don't, I need to know. Flames welcome.

                            Comment

                            • Martin Dickopp

                              #15
                              Re: write a binary file?

                              k_amir7@yahoo.c om (kal) writes:
                              [color=blue][color=green]
                              >> Use shifts and mask operations (bitwise AND) to extract the individual
                              >> bytes. The details depend on the byte order in which you want to write
                              >> to the file.[/color]
                              >
                              > IMHO one is better off using "htnl()."[/color]

                              Wheather such a non-standard method of doing things is preferable when a
                              standard method exists is certainly debatable.

                              Martin


                              --
                              ,--. Martin Dickopp, Dresden, Germany ,= ,-_-. =.
                              / ,- ) http://www.zero-based.org/ ((_/)o o(\_))
                              \ `-' `-'(. .)`-'
                              `-. Debian, a variant of the GNU operating system. \_/

                              Comment

                              Working...