Jump to content

Trouble with file input/output

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
LoneWolf

LoneWolf

    Newbie

  • Members
  • PipPip
  • 10 posts
I'm writing a simple program that creates a .dat file and stores data from objects of the class Client. When I use the program to write data into the file, it apparently runs successfully, but when I try to read the file and output its contents on the screen, the computer beeps twice and shows a lot of weird things. My code seems to be right, so I don't know what is going on.
I'm attaching the project files within this thread, the main.cpp initializes the file (creates and write the data into the file) and the reader.cpp file reads what was written into the .dat file.

Attached Files



#2
Lance

Lance

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 276 posts

Quote

class Client
{
private:
int accountNumber; //Client's Account Number
string name; //Client's Name
double balance; //Client's Balance

You should not use string name, use

char name[MAX_NAME_LEN];

Very interesting, in a reply to a post by ProgrammingChild, Muted did virtually the same thing as you were doing. He's more lucky, he use char *, the the const char * msg remain valid within the session. The function runs, but nontheless it was wrong, as wrong as in your case.

#3
Lance

Lance

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 276 posts
for detailed discussion, refer to
http://forum.codecal...ad-my-post.html

#4
Lance

Lance

    Programming Professional

  • Members
  • PipPipPipPipPip
  • 276 posts
Simply put, you should not write an incomplete object to a file and expect to be able to reload it without losing its integrity.

in it's internal, a std::string maintains a char * data to a dynamically new[]'d array. Let's say, when you save it, data is pointing to 0x40000000, and at that location is a ASCII string "Hello world". Now do you think when you save the Client object, "Hello world" is also saved?

Obviously it's not. Then the client object is destructed. in the destruction process, the array pointed by data is delete[]'d. Then you reload your client object, in the process, it's led to believe that it owns the location 0x40000000 which is not true. Access violation occurred and you're kicked out.

Edited by Lance, 03 February 2009 - 12:33 PM.
spelling