Thread: Writting a struct to a file

  1. #1
    Registered User
    Join Date
    Sep 2013
    Posts
    4

    Writting a struct to a file

    Hi, I am trying to write a structure to a file. Example say the structure has two variables x and y . I want to write a function which modifies these variables and stores the modified version on a file. Such that next time I call the function . it has the values from the previous write.

    Here's an example of my code .
    Code:
    // initialize the structure struct->x = 0, struct->y = 0
    
    File *fp = fopen("filename", "r+");
    struct MYSTRUCT mystruct = (struct MYSTRUCT*)malloc(sizeof(MYSTRUCT))
    //check 
    fread (mystruct, sizeof(MYSTRUCT), 1, fp);
    
    // do some calculations.
    
    fwrite(mystruct, sizeof(MYSTRUCT), 1, fp);
    
    fclose(fp)
    
    //return some value
    }
    The problem is that each time I run the program it shows the initialized value of the variables and not the value from last write. I guess the write isn't successful because when I open in w+ mode. i get the error file could not be opened and then i have to delete the file and re create it

  2. #2
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    The fwrite is probably working, but it's writing the values after the initial values since that will be the current file position after the fread.
    To overwrite the original values you could use rewind(fp) before the fwrite.
    I'm assuming that this data is all the file contains (or that it is at least at the beginning of the file).
    The cost of software maintenance increases with the square of the programmer's creativity. - Robert D. Bliss

  3. #3
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    You should probably also be using the binary open mode as well.

    Jim

  4. #4
    Registered User
    Join Date
    Sep 2013
    Posts
    4
    It worked. Thanks a lot

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. writting to a binary file
    By baxy in forum C++ Programming
    Replies: 5
    Last Post: 08-05-2013, 08:34 AM
  2. Writting to file in callback function
    By Median in forum C++ Programming
    Replies: 10
    Last Post: 04-02-2013, 05:18 PM
  3. Writting in a file (simple question...)
    By C_ntua in forum C Programming
    Replies: 6
    Last Post: 06-17-2008, 02:00 PM
  4. Writting to a text file
    By Andy123 in forum C Programming
    Replies: 1
    Last Post: 05-24-2006, 06:40 AM
  5. What can I ask about problems of writting a .bat file?
    By DramaKing in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 11-13-2001, 03:53 AM

Tags for this Thread