Click here to Skip to main content
15,894,313 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello. I'm trying to write and read from a binary file and I having some problems when I try to load the data that contains chars.

C++
 struct user {
	char *username;
	char * password;
	unsigned int ID;
 };


test_usernames_c.open("users_c.dta", ios::binary | ios::out);
user *default_user;
default_user = new user;

default_user->username = new char[7];
strcpy_s(default_user->username,7, "user11");

test_usernames_c.write((const char*)&default_user->username, 7);
//I hardcoded the size just to make sure 


test_usernames_c.close();

char *usernameX;
usernameX = new char[7];

test_usernames_c.seekg(pos_file, ios::beg);
test_usernames_c.read((char*)&usernameX, sizeof(char) * 7);


When I read the file at the end of the code I get the correct result but I get CORRUPTED STACK and Visual Studio throws an exception (Run-Time Check Failure #2 - Stack around the variable 'usernameX' was corrupted.)

Can you please tell me how to correct the code or what Im doing wrong? If I try to read the data in a user struct it works but I dont understand why since I initiate the char* in the struct and the standalone usernameX char* in the same way.
Posted
Comments
bobos_underground 18-Dec-14 17:57pm    
After I close the file I open it again with ios::in; And also seekg is irelevant;

Look at cplusplus website. They have:

C#
char * buffer = new char [length];

    std::cout << "Reading " << length << " characters... ";
    // read data as a block:
    is.read (buffer,length);


you don't need this:
(char*)&


does that solve your problem?
 
Share this answer
 
Comments
bobos_underground 18-Dec-14 19:01pm    
Thank you.
bobos_underground 18-Dec-14 19:07pm    
But its normal to write chars in the binary file so that are readable to an text editor ?
Your buffer addressing is wrong, it should be:
C++
test_usernames_c.write(default_user->username, 7); // username is already a pointer
//I hardcoded the size just to make sure 

test_usernames_c.close();
 
char *usernameX;
usernameX = new char[7];
 
test_usernames_c.seekg(pos_file, ios::beg);
test_usernames_c.read(usernameX, sizeof(char) * 7); // usernameX is also a pointer
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900