storing string objects to binary files

This is a discussion on storing string objects to binary files within the C++ Programming forums, part of the General Programming Boards category; Hi, Can anyone suggest a good method to store string objects to binary files? If we simply, store the string ...

  1. #1
    Unregistered
    Guest

    storing string objects to binary files

    Hi,
    Can anyone suggest a good method to store string objects to binary files? If we simply, store the string object, then when we need to read it, we won't know the length to read, right?

    Currently, what I have is before storing each string, I store the length of the string as an int first... So, when reading the file, I read the int so I know the length of the string to be read.

    Question is, Is this an efficient way to do it? Does anyone know of a better way? Thanks in advance.

  2. #2
    Registered User
    Join Date
    Sep 2001
    Posts
    156
    You could use the same convention that the string functions such as strlen, strcpy, etc use. That is to write out a NULL byte at the end of the character array which is what a string typically is. Then when reading the string and you encounter the NULL you're at the end.

  3. #3
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Unless you need to save space, you could just declare the string as a character array of a fixed size, then write out the whole buffer. When you read it back it, it will have the string terminator. This is also good if you write out a structure which has data of different types.
    Code:
    #include <stdlib.h>
    #include <fstream.h>
    
    int main()
    {
       int i;
       char city[80];
       char cities[10][80] = 
       {"Dallas","Paris","Rome","Las Vegas","London",
       "Athens","Los Angeles","San Diego","Madrid","Tampa Bay"};
    
       remove("cities.dat");
       ofstream out("cities.dat",ios::binary);
       for (i=0; i<10; i++)
          out.write(cities[i],80);
       out.close();
    
       ifstream in("cities.dat",ios::binary);
       for (i=0; i<10; i++)
       {
          in.read(city,80);
          cout << "city:" << city << "...\n";
       }
       in.close();
    
       return 0;
    }
    Last edited by swoopy; 10-07-2001 at 12:38 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Custom String class gives problem with another prog.
    By I BLcK I in forum C++ Programming
    Replies: 1
    Last Post: 12-18-2006, 03:40 AM
  2. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  3. Binary to string
    By Stack Overflow in forum C Programming
    Replies: 8
    Last Post: 04-23-2004, 08:33 AM
  4. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  5. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21