Thread: Writing a structure to file?

  1. #1
    Unregistered
    Guest

    Question Writing a structure to file?

    Is it possible to save an entire structure at a time to a file? In the code I’ve attached I am saving the pointer, but not the information stored, how can I do it?


    void filesave(void)
    {
    FILE *fpout;

    out=first;

    if(out==(struct account *)NULL)
    {
    puts("There are no records to Save!");
    system("pause");
    }
    else
    {
    if ((fpout = fopen("test.txt","w")) == NULL)
    fprintf (fpout,"%s\n", out);
    }

    puts("Files Copied!");
    system("pause");

    fclose(fpout);
    }

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    752
    Depends on the structure. ALthough in general, the following call MIGHT work....

    fwrite (out, sizeof (struct account), 1, fpout);

    I repeat, it MIGHT work. You would read the structure from the file using an fread() call with the same parameters.
    Callou collei we'll code the way
    Of prime numbers and pings!

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > Is it possible to save an entire structure at a time to a file?
    Yes, providing the structure does not contain any pointers

    Code:
    struct foo bar[10];
    FILE *fp = fopen( "file.dat", "wb" );
    fwrite( bar, sizeof(struct foo), 10, fp );
    fclose( fp );
    You should always use binary mode ("rb","wb") when you're using the fread/fwrite functions.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. To find the memory leaks without using any tools
    By asadullah in forum C Programming
    Replies: 2
    Last Post: 05-12-2008, 07:54 AM
  2. help with text input
    By Alphawaves in forum C Programming
    Replies: 8
    Last Post: 04-08-2007, 04:54 PM
  3. Possible circular definition with singleton objects
    By techrolla in forum C++ Programming
    Replies: 3
    Last Post: 12-26-2004, 10:46 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. System
    By drdroid in forum C++ Programming
    Replies: 3
    Last Post: 06-28-2002, 10:12 PM