Binary files

This is a discussion on Binary files within the C Programming forums, part of the General Programming Boards category; Hi! I'm wanting to learn how to do binary files, but the FAQ example is a bit too complicated for ...

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    207

    Binary files

    Hi!

    I'm wanting to learn how to do binary files, but the FAQ example is a bit too complicated for me to follow. Are structs absolutely necessary for binary files?

    All I want to do is create a random-access file and use the data in the file as an array. I don't want to load any of it into a pointer/structure/array, I just want to manipulate the data directly.

    Does my question make sense? I'm trying to upgrade my previous program:

    Type casting

    So that I use a binary file instead of a pointer.

    Are there any basic examples for binary files that show how to:

    1) create
    2) write the initial data
    3) move around in it to access different records
    4) change data in a "random" record

    Thanks!

    mw

  2. #2
    Banned
    Join Date
    Jun 2005
    Posts
    594
    create a file

    FILE * file;
    file = fopen("filename.ext","wb"); //w for write b for binary

    i think that right i mostly do the c++ way when working
    with files so i dont remember if that correct or not.


    to read from a file in binary i believe its

    char ch;
    file.fread((char*) ch, sizeof( ch ) ); //if that correct it read one character from the file.

    wow i really dont remember c way of it at all c++ so much better

    and to move aroudn in the file i believe the function is

    fseek()

    clearly i dotn remember the correct usage of some of these
    function but all you need to do is google the function to
    figure out how to use it.


    as for manipulating data in the record, you would obviously
    need to be fimilar with how the file looks inside,
    either setup a certian outline for the data in the file, or
    learn how to manipulate what already in there.
    then you can read thru the data till you find a specific
    record and there ya go.

    sorry i couldnt be as detailed as i wanted to be, if
    you change to c++ then holla at me and ill hoook you up
    Last edited by ILoveVectors; 08-21-2005 at 11:23 PM.

  3. #3
    Registered User
    Join Date
    May 2005
    Posts
    207
    Uh- Thanks?

    mw

  4. #4
    Banned
    Join Date
    Jun 2005
    Posts
    594
    no one else seem to has a answer right now for ya,
    so that best i can do seeing as i cant remember much
    C specific things. however im sure you will get alot
    more responses if you actually attempted it, and posted
    you code where your having problems.

  5. #5
    Registered User
    Join Date
    May 2005
    Posts
    207
    It's cool. I was trying your code out. In the meantime, I also seem to be having trouble with "fclose". Based on past experiences, I assume this means I'm probably having trouble with "fopen":

    Code:
    #include <stdio.h>
    
    //prototypes
    int start_binary (void);
    
    int main (void)
    {
        start_binary ()
    
        return (0);
    }
    
    int start_binary (void)
    {
        FILE *fp = fopen ("prime_binary.txt", "wb");
    
        fclose (fp);
    
        if (!fp)
        {
            printf ("Close successful");
    
            return (0);
        }
        else
        {
            printf ("Close failed");
        }
    
        printf ("\n\n");
        return (0);
    }
    It compiles correctly, but the output I get is "Close failed". Does anyone know why I'm getting this?

    mw

    PS: An empty "prime_binary.txt" file was created by the program. So maybe my "if" statement is incorrect?
    Last edited by Lionmane; 08-22-2005 at 12:14 AM.

  6. #6
    Banned
    Join Date
    Jun 2005
    Posts
    594
    ive never see them check if a file had been closed before

    also you should check this out

    my guess on that would be, if the file had been closed correctly
    it would prolly return a non-zero value, meaning
    that it would return true, but since your doing the opposite,
    ( ! ), if it had come back true that it was closed, it would say false
    and run the else statment. that just a guess though.

    then again fp is a pointer right, so once the file
    is closed id imagine that fp would be pointing at junk
    iin memory, so i dont think taht the correct way of coing about it.


    maybe this is a possiblity

    if( fclose( fp ) )

    liek i said c++ i so much awsomer :O
    Last edited by ILoveVectors; 08-22-2005 at 12:18 AM.

  7. #7
    Registered User
    Join Date
    May 2005
    Posts
    207
    Oh yeah... Duh. Well that was easy. I changed my "if" statement to this:

    if (fclose(fp))

    and it worked correctly.

    Hey thanks for the link! I was reading this:
    http://faq.cprogramming.com/cgi-bin/...&id=1043284392

    But it's Level 2.

    mw

  8. #8
    Registered User
    Join Date
    May 2005
    Posts
    207
    Hey, it just created a simple text file that I can open in Notepad! That was easy! QBasic creates a messy binary file that's illegible with Notepad.

    Does this mean that I can open *any* text file as a binary file, assuming I correctly describe it to my program?

    mw

  9. #9
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,506
    > Does this mean that I can open *any* text file as a binary file, assuming I correctly describe it to my program?
    Yes.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  10. #10
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    What you should actually do is check the return value of fopen to see if it failed.
    Code:
    FILE *fp;
    if((fp=fopen(filename, mode)) == NULL) {
        /* report error */
    }
    fclose cannot modify what fp points to. It can only modify what fp is pointing to. Therefore, fp must hold fopen()'s return value. In your code
    Code:
    int start_binary (void)
    {
        FILE *fp = fopen ("prime_binary.txt", "wb");
    
        fclose (fp);
    
        if (!fp)
        {
            printf ("Close successful");
    
            return (0);
        }
        else
        {
            printf ("Close failed");
        }
    
        printf ("\n\n");
        return (0);
    }
    You're just checking if fopen failed. But you should check if fopen failed before you start using the filehandle.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  11. #11
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    ILoveVectors:
    Code:
    file.fread((char*) ch, sizeof( ch ) );
    file is a structure. Also, the first argument is a void pointer, so no cast is required. fread takes three arguments, and is usually used in conjunction with fwrite (otherwise you tend to get gibberish).
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  12. #12
    Registered User
    Join Date
    May 2005
    Posts
    207
    Hmm... I seem to have more questions:

    Code:
    #include <stdio.h>
    
    //prototypes
    int start_binary (void);
    void scope_test (void);
    
    int main (void)
    {
        start_binary ();
    
        return (0);
    }
    
    int start_binary (void)
    {
        char x[10] = "ABCDEFGHIJ";
        FILE *fp = fopen ("prime_binary.txt", "wb");
    
        if (!fp)
        {
            printf ("\n\nERROR!  Not enough memory!\n\n");
    
            return (0);
        }
    
        fwrite (x, sizeof (x[0]), sizeof (x) / sizeof (x[0]), fp);
    
        scope_test ();
    
        fclose (fp);
        printf ("\n\n");
        return (0);
    }
    
    void scope_test (void)
    {
        int loop = 0;
        char x[10] = "JIHGFEDCBA";
    
        FILE *fp = fopen ("prime_binary.txt", "a");
    
        for (loop = 0; loop < 10; loop++)
        {
            fprintf (fp, "%c", x[loop]);
        }
    
        fclose (fp);
    }
    (If there are any syntax errors, I apologize. I'm on a seperate computer and had to retype it here)

    When I run this program:

    1) Why doesn't Windows crash when I attempt to open a file twice (especially in different modes)?

    2) Why do I only have 1 line instead of 2 in my text file after this program is finished running? I was trying to "append" in my scope_test function to see what would happen.

    Thanks!

    mw
    Last edited by Lionmane; 08-23-2005 at 12:38 AM.

  13. #13
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,506
    > (If there are any syntax errors, I apologize. I'm on a seperate computer and had to retype it here)
    I suggest you only post the code you try in future.

    By the time you've posted what you think you have, we've responded to what we think you meant, you've taken away what you think we've said back to your other machine, the result is nothing like what you started with.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  14. #14
    Registered User
    Join Date
    May 2005
    Posts
    207
    I program on a laptop. I set my laptop next to the computer and type from that. My code matches as near as I can make it.

    Why didn't you answer my question? The next time you post a response to someone's question, try to be a little less inept at it.

    mw

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by Lionmane
    Why didn't you answer my question? The next time you post a response to someone's question, try to be a little less inept at it.
    Don't use big words you don't know the meaning of. You just look like an idiot trying to mimic Salem.

    1) Show me in the standard where it says Windows has to crash because you call fopen twice on the same file.
    2) What the hell did you expect? Why should it keep both of your changes when you open the file twice? How can that even remotely be correct? How on earth could you be so stupid as to think that is even remotely correct? Now you're surprised it doesn't work? What?


    Quzah.
    Hope is the first step on the road to disappointment.

Page 1 of 3 123 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Linking header files, Source files and main program(Accel. C++)
    By Daniel Primed in forum C++ Programming
    Replies: 3
    Last Post: 01-17-2006, 10:46 AM
  2. send/recv binary files using sockets in C++
    By dafatdude in forum Networking/Device Communication
    Replies: 14
    Last Post: 07-25-2004, 11:00 AM
  3. MFC: CStrings & binary files question(s)
    By BrianK in forum Windows Programming
    Replies: 0
    Last Post: 06-24-2004, 05:41 PM
  4. Binary files
    By Brian in forum C Programming
    Replies: 2
    Last Post: 02-18-2002, 12:13 PM
  5. storing string objects to binary files
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 10-06-2001, 11:33 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21