Reading File in to a pointer

Started by
13 comments, last by rip-off 9 years, 4 months ago

nvm.. delete this post please.

Advertisement
A pointer always points to a location in (virtual) memory. Just like an address (1234 Park Drive, Beijing, Australia). But before you can write or read from an location in memory, this memory has to be allocated to your program. The OS does this for you, but you have to "say" that you need memory and how much. Simply use char* Ptr = new char[100]; for this if you want to allocate memory for 100 chars. Ptr will point to this memory and not to Beijing anymore - which is not in Australia (afaik). If you use it in the read function, read will copy the content from the file to the location Ptr points to.

If you write char* Test = "1234"; this memory is located in the data section, which is saved in your compiled program and stored in read-only memory when running this program. You can read "1234", but you cannot write to its location.

If you write char Test1='a'; char* Ptr1=&Test1; Test1 has been put on the stack. Ptr1 will point to this location in the stack, but the stack will change when you leave the block (begins with {, ends with } and can contain other blocks) in which Test1 is defined. But you can use Ptr1 and Test1 as parameters for functions if you call them within the block in which they are defined.

I hope I didn't forget something important...

So If I write like this in the file how I read the file later using just a char pointer ? (For example If I want to use char *usernameX and initialize it with size of 7 characters in memory to read to it)


 
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 solve it. I used test_usernames_c.write(default_user->username, 7) instead with (char*)& and it worked. Thanks for the help and answers.

Remember that when you cast, you're telling the compiler that you know exactly what you're doing. You always need to be very careful in such situations.

A side note is that magic numbers like "7" are confusing to read and prone to error (e.g. you might change the name but forget to update this value).

I'd recommend explicitly using std::strlen() to be on the safe side - or better still, use std::string:

struct user {
    std::string username;
    std::string password;
};
 
user default_user;
default_user.username = "user";
default_user.password = "1234";
 
users_file.open("users_c.dta", ios::binary | ios::out);
users_file.write(default_user.username.c_str(), sizeof(char) * default_user.username.length() + 1));
users_file.write(default_user.password.c_str(), sizeof(char) * default_user.password.length() + 1));

You'll also note that the "typedef struct _foo { ... } foo;" idiom is not necessary in C++.

This topic is closed to new replies.

Advertisement