Thread: storing string objects to binary files

  1. #1

    storing string objects to binary files

    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
    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
    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.
    #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"};
       ofstream out("cities.dat",ios::binary);
       for (i=0; i<10; i++)
       ifstream in("cities.dat",ios::binary);
       for (i=0; i<10; i++)
          cout << "city:" << city << "...\n";
       return 0;
    Last edited by swoopy; 10-06-2001 at 11:38 PM.

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, 07: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