How to read and write data in C++ (random access)?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Man4ish
    New Member
    • Mar 2008
    • 151

    How to read and write data in C++ (random access)?

    Hi,

    I have one input data.

    1200 3
    1234 4
    1235 6
    1236 2

    I need write this in binary file in such a way that i can easily write and read the data.

    I know using fread and fwrite it is possible to do it. we can access data randomly. But how can i implement it? Any working example will help me.
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    Use a struct:

    Code:
    struct
    {
      int data;
      int data1;
    };
    Load the members and then write the struct in binary to your file. You on't need the separating space on the output.

    Read the input using fscanf into an int, a char, and an int. Use the ints to load yout struct.

    Comment

    • Man4ish
      New Member
      • Mar 2008
      • 151

      #3
      But i want to write data in such a way that 3 should be stored at 1200 loction and like others and i can easily read the data from there also.

      Regards

      Comment

      • weaknessforcats
        Recognized Expert Expert
        • Mar 2007
        • 9214

        #4
        In that case use a text file instead of a binary file and be sure to write each record in the file in exactly the same format.

        A struct and a binary file will still work since the file would contain nothing but ints that are all the same size. The int with 1200 would be followed by an int with 3 followed by an int with 1234.

        Remember, after the file is written there is no way to tell howit was written just from the data in the file. It is up to you to position the data so you can access it randomly later. In this case, do you see the data as 4 characters 1234 or an integer of 1234. The answer to that will determine how to format the file.

        Comment

        Working...