Archived

This topic is now archived and is closed to further replies.

CoolGames

ReadFile with struct->char*

Recommended Posts

Hi All! I just want to read a char* in a pointed structure from a file... dont know how. Please help me. My code: typedef struct { DWORD id; char* name; } PERSON; PERSON *person; person = new PERSON; DWORD BytesRead; // How to set a char* to a length of 6 ?? person->name = "123456"; // hFile is not overlapped, and it works fine when I replace person->char* to BYTE b[6]... if (ReadFile(hFile, person->name, 6, &BytesRead, 0) == 1) {// This ReadFile never returns 1 when I use person->name as parameter printf("OK\n"); } printf("%s", person->name); And maybe the same question: I cant get the simple following code to work (gives an exception). I just want to copy 6 bytes from b to name: char* name; BYTE b[6]; name = "123456"; memcpy(name, b, 6); Thanx very much for every help!!!

Share this post


Link to post
Share on other sites
PERSON::name is a pointer to a character, but when a instantiate a PERSON object, that pointer doesn''t point to anything. You first have to allocate memory where you can store the characters of the person''s name. If you know how long a name will be, you can make PERSON::name an array of char:
  
struct PERSON {
int id;
char name[6]; // name can be FIVE characters (remember the terminating 0 of a string!)

};


Another option is to allocate an array of chars using new. You have to remember to delete that array, though:
  
struct PERSON {
int id;
char* name;
};

PERSON* person = new PERSON;
person->name = new char[6];

delete[] person->name;
delete person;


Once you have allocated storage for the name, you can read it in from file. The ReadFile code you use will work then, but remember to either read the terminating zero, or append one manually after you''ve read the characters. If you don''t have an appended zero, the various str functions won''t work.

Your second problem resembles the first: you have to allocate storage to store the characters. Remember, char* only makes room in memory to store an address, since char* is a pointer. You have to allocate the memory to store the data yourself.

HTH

Share this post


Link to post
Share on other sites