Results 1 to 10 of 10

Thread: Problums writeing struct to a file C++

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Aug 2002
    Location
    UK
    Posts
    417

    Problums writeing struct to a file C++

    hi all, C++ beginner needs help.

    I decided today to give C++ FileIo Streams a little go. since I not played with them much before and have not started out very well

    anyway I desided to make a little project that can save the contents of a struct to a file. pretty basic in fact.

    My problum is reading back the info. the letter and number displays ok but for some reason str is not. anyway I left my code below if that helps.

    VB Code:
    1. #include <iostream>
    2. #include <fstream>
    3. using namespace std;
    4.  
    5. struct test
    6. {
    7.     int number;
    8.     char letter;
    9.     char *str;
    10. } aTest;
    11.  
    12.  
    13. int main(int agvc)
    14. {
    15.     ofstream fout;
    16.     ifstream fin;
    17.     // fill struct with some random data
    18.     aTest.number = 245;
    19.     aTest.letter = 'A';
    20.  
    21.     //What am I doing wrong here I wonder
    22.     aTest.str = (char*) malloc(100);
    23.     strcpy(aTest.str,"Hello World this is a long string");
    24.  
    25.  
    26.     //write the struct to the file
    27.    
    28.     fout.open("C:\\test.txt",ios::binary);
    29.     fout.write((char*)(&aTest),sizeof(aTest));
    30.     fout.close();
    31.    
    32.     // Clear struct of it's data I am only new in C++
    33.     // So i am not sure this is the correct way to clear stuff out
    34.     // tho for the example it be ok I think
    35.     aTest.letter = '\0';
    36.     aTest.number = 0;
    37.     strcpy(aTest.str,"\0");
    38.     //Load the struct back in so we can display the data
    39.  
    40.     fin.open("c:\\test.txt",ios::binary);
    41.     fin.read((char*)(&aTest),sizeof(aTest));
    42.     fin.close();
    43.  
    44.     // display the data
    45.     std::cout << "Number: " << aTest.number << "\n";
    46.     std::cout << "Letter: " << aTest.letter << "\n";
    47.     std::cout << "String: " << aTest.str << "\n"; // :( why is my str not showing
    48.  
    49. }

    anyway hope someone can help
    Thanks.
    When your dreams come true.
    On error resume pulling hair out.

  2. #2
    Smitten by reality Harsh Gupta's Avatar
    Join Date
    Feb 2005
    Posts
    2,938

    Re: Problums writeing struct to a file C++

    well i haven't tried your code but i think u r making 1 mistake n not writing 1 statement:

    1) u r closing the file before displaying the values, and
    2) use getch(); [header file conio.h] at the end of the code, before the closing bracelet of main().

    i think that shud work!!! maybe closing file after wont change anything but yes, u need to put getch() in your code!!!
    Show Appreciation. Rate Posts.

  3. #3

    Thread Starter
    Hyperactive Member
    Join Date
    Aug 2002
    Location
    UK
    Posts
    417

    Re: Problums writeing struct to a file C++

    hi, Harsh

    I am not sure what you mean. all data has been written to the file. that's why I am closeing it.

    I only cleared the struct information once it's been saved to the file. and then I reload the file back in.

    The problum is eveything else in the struct is showing all except this line.

    std::cout << "String: " << aTest.str << "\n"; // why is my str not showing

    any other ideas.
    When your dreams come true.
    On error resume pulling hair out.

  4. #4
    Smitten by reality Harsh Gupta's Avatar
    Join Date
    Feb 2005
    Posts
    2,938

    Re: Problums writeing struct to a file C++

    Quote Originally Posted by dreamvb
    hi, Harsh

    I am not sure what you mean. all data has been written to the file. that's why I am closeing it.

    I only cleared the struct information once it's been saved to the file. and then I reload the file back in.

    The problum is eveything else in the struct is showing all except this line.

    std::cout << "String: " << aTest.str << "\n"; // why is my str not showing

    any other ideas.
    sorry didn't read the whole post, my bad!!!

    maybe in that case there is something wrong in
    VB Code:
    1. strcpy(aTest.str,"\0");
    just comment it out n then try compiling it.........probably it may work!!!!
    Show Appreciation. Rate Posts.

  5. #5
    Kitten CornedBee's Avatar
    Join Date
    Aug 2001
    Location
    In a microchip!
    Posts
    11,594

    Re: Problums writeing struct to a file C++

    You're saving a pointer, not the character data. You need to save character data independently, usually with the length saved first.
    All the buzzt
    CornedBee

    "Writing specifications is like writing a novel. Writing code is like writing poetry."
    - Anonymous, published by Raymond Chen

    Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.

  6. #6

    Thread Starter
    Hyperactive Member
    Join Date
    Aug 2002
    Location
    UK
    Posts
    417

    Re: Problums writeing struct to a file C++

    Hi CornedBee,

    Can you give me a little example as I am still really leraning. if you have time thanks.
    When your dreams come true.
    On error resume pulling hair out.

  7. #7

    Thread Starter
    Hyperactive Member
    Join Date
    Aug 2002
    Location
    UK
    Posts
    417

    Re: Problums writeing struct to a file C++

    bump*
    When your dreams come true.
    On error resume pulling hair out.

  8. #8
    Fanatic Member riis's Avatar
    Join Date
    Nov 2001
    Posts
    551

    Re: Problums writeing struct to a file C++

    Writing the string
    Code:
    char *str;
    int stringLen = 100;
    
    str = new char[stringLen];   // Allocate memory the C++ way if you're using C++
    memset(str, 0, stringLen);   // The new operator doesn't clear memory automatically, and you certainly don't want to have garbage in your file
    strcpy(str, "This is a long string that should be less than 100 chars");   // The string to be copied should be at most 99 chars
    
    std::ofstream fOut("c:\\temp\\myfile.dat", std::ios::binary);
    // Check if the file has opened, etc...
    fOut.write(reinterpret_cast<char *>(&stringLen), sizeof(int));   // Using reinterpret_cast, so this ugly syntax reminds you that you're doing something that you shouldn't, but have to. It's also the proper C++ way to cast
    fOut.write(str, stringLen);
    fOut.close();
    
    delete[] str;   // Clear the allocated memory
    Alternatively, you can calculate the length of the actual string (stringLen = strlen(str), and write that value to the file.

    Reading the string:
    Code:
    char *str;
    int stringLen;
    std::ifstream fIn("c:\\temp\\myfile.dat", std::ios::binary);
    // Check if the file has opened, etc...
    fIn.read(reinterpret_cast<char *>(&stringLen), sizeof(int));   // Read the length first
    str = new char[stringLen + 1];   // Allocate sufficient memory, including the null character
    fIn.read(str, stringLen);
    fIn.close();
    
    // Note that when you didn't calculate the new value for stringLen in the above code, this stringLen will hold a value which is larger than the actual string size
    std::cout << "String length: " << stringLen << std::endl;
    std::cout << "String value: " << str << std::endl;
    delete[] str;
    Hope this helps
    Last edited by riis; Oct 28th, 2005 at 02:00 PM.

  9. #9
    Fanatic Member riis's Avatar
    Join Date
    Nov 2001
    Posts
    551

    Re: Problums writeing struct to a file C++

    In case you want this to be a part of a struct/class, you should create methods named "read" and "write" (or what you prefer). Since these methods are part of the struct/class, they have the knowledge how to read from/write to the file.

    If the file also contains information that doesn't belong to this class, then the calling code should be responsible for opening/closing the file and reading/writing other information.

  10. #10
    Fanatic Member riis's Avatar
    Join Date
    Nov 2001
    Posts
    551

    Re: Problums writeing struct to a file C++

    Quote Originally Posted by dreamvb
    fout.open("C:\\test.txt",ios::binary);
    I wouldn't give a binary file a TXT extension

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width