Thread: Write/Read tree nodes into a binary file

  1. #1
    Registered User
    Join Date
    Oct 2012

    Write/Read tree nodes into a binary file

    Hello everyone,

    I have a binary tree, and I want to store all information its leaves stores into a binary file and then read it.

    What I tried:

    A function that reads the tree, and whenever it finds a leaf, it writes in the binary file:

    if(tree->right == NULL && tree->left == NULL){
           fwrite(tree, sizeof(tree), 1, output);
    and in the main function:

           fread(tree, sizeof(tree), 1, output);
           printf("This is the leaf number %d", tree->num);

    I'm trying to read 5 nodes just to see if its working but it isn't. The output shows the first node of the tree everytime.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    My Hat of Guessing has come up with some possibilities (since it's not like you gave us any information):
    1. Make sure you are doing a proper tree traversal.
    2. Make sure you don't open and close the file a bunch of times (for instance, every time you open a file in "w" mode, you trash the previously-existing contents).
    3. Have your operating system tell you the size of the file, to make sure it is as big as you think it is. (You can do this post facto, right now even, assuming you haven't deleted your data file.)
    4. Make sure your num values are set appropriately (ie if every node has the same num value for whatever reason, then they will all look the same).

  3. #3
    Registered User
    Join Date
    Dec 2012
    You are using "fread" with a variable called "output". That is a bit strange.

    Did you open the file in read/write mode? Something like "w+b".

    Did you call "rewind()" or "fseek()" before trying to read the file? You should ;-)

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 12
    Last Post: 06-18-2012, 08:23 AM
  2. Read and write binary file?
    By Loic in forum C++ Programming
    Replies: 2
    Last Post: 10-29-2008, 05:31 PM
  3. Binary Tree - sum of nodes
    By Tiffanie in forum C++ Programming
    Replies: 1
    Last Post: 09-15-2008, 08:49 AM
  4. Replies: 1
    Last Post: 04-26-2008, 07:04 PM
  5. Copy/Read/Write a binary file(.mp3)
    By swapnaoe in forum C Programming
    Replies: 9
    Last Post: 04-22-2008, 02:38 AM