Thread: Writing Data to a File

  1. #1
    Unregistered
    Guest

    Writing Data to a File

    I'm trying to write some structures (structures contain only 1 word and 2 pointers) too a text file. My code is only writing 1 word too the text file.

    Could someone please tell me how to create this file so that the words are 1 to a line.

    A
    bit
    like
    this.

    Here is my code that is not working properly:

    void Order(TreePointer Root)
    {
    FILE *filePtr;

    if(Root != NULL)
    {
    if((filePtr = fopen("dict.txt","a+")) == NULL)
    printf("File could not be created!\n");

    Order(Root->Left);

    fwrite(Root->Data, sizeof(struct TreeNode),1,filePtr);
    Order(Root->Right);
    fclose(filePtr);
    }
    }


    Many thanx.

  2. #2
    Registered User
    Join Date
    Dec 2001
    Posts
    88
    mhm...
    why do you write using fwrite? I thought you don't want to write the pointers to the file?

    use fputs instead and write only the word

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,656
    You're opening the file each time

    And you should only write the data, not the pointers as well

    Code:
    void Order(TreePointer Root, FILE *filePtr ) {
      if ( Root == NULL ) return;
      Order(Root->Left); 
      fprintf( filePtr, "%s\n", Root->Data );
    //  fwrite(Root->Data, sizeof(Root->Data),1,filePtr); 
      Order(Root->Right); 
    }
    You open the file before you call this function, then close it after the function returns

    If you want a binary file, use the fwrite
    If you want a text file (as you seem to suggest), then use fprintf

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. File Writing Problem
    By polskash in forum C Programming
    Replies: 3
    Last Post: 02-13-2009, 10:47 AM
  3. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM
  4. archive format
    By Nor in forum A Brief History of Cprogramming.com
    Replies: 0
    Last Post: 08-05-2003, 07:01 PM
  5. Need a suggestion on a school project..
    By Screwz Luse in forum C Programming
    Replies: 5
    Last Post: 11-27-2001, 02:58 AM