Click to See Complete Forum and Search --> : Message box w/variable problem


esselfe
May 26th, 2006, 02:57 PM
Hi!

I have to communicate a message to the user with a MessageBox function that takes as second argument a variable. This variable contains data extracted from a log ASCII-text file. As the message box is shown, the message displayed is not exactly the same as the logfile. The main content is there, but there are about 10 chars looking like "««««««««ÞÎÞÎÞ"!

There's the source for Visual c++ express in empty type project:

#include <windows.h>
#include <fstream>
using namespace std;

int main(){
ofstream ofs("test.mee", ios::out);
ofs <<"test again!";
ofs.close();

ifstream ifs("test.mee", ios::out);
// get file size
ifs.seekg(0, ios::end);
int filesize =ifs.tellg();
ifs.seekg(0, ios::beg);
// proceed
char *buffer1;
buffer1 =new char [filesize];
ifs.read(buffer1, filesize);
ifs.close();
MessageBox(NULL,buffer1,"esselfe",MB_OK);
return 0;
}

Do you think 'filesize' has taken in consideration the OS data such as timestamp?
I compiled this code under Dev-c++ IDE and it compiled correctly...

What is the problem?!

golanshahar
May 26th, 2006, 03:11 PM
Looks like your string buffer doenst have '\0' in the end.

try this:

char *buffer1;
buffer1 =new char [filesize];
memset(buffer1,0,filesize);
ifs.read(buffer1, filesize);


NOTE: in your code there is memory leak you dont delete[] the buffer1

Cheers

Andreas Masur
May 26th, 2006, 05:20 PM
try this:

char *buffer1;
buffer1 =new char [filesize];
memset(buffer1,0,filesize);
ifs.read(buffer1, filesize);


This wouldn't help since you still wouldn't have a terminating zero at the end...either make the array one bigger

char *buffer1;
buffer1 =new char [filesize + 1];
memset(buffer1, 0, filesize);
ifs.read(buffer1, filesize);

or receive one less character

char *buffer1;
buffer1 =new char [filesize];
memset(buffer1, 0, filesize);
ifs.read(buffer1, filesize - 1);

golanshahar
May 26th, 2006, 05:28 PM
This wouldn't help since you still wouldn't have a terminating zero at the end...either make the array one bigger

char *buffer1;
buffer1 =new char [filesize + 1];
memset(buffer1, 0, filesize);
ifs.read(buffer1, filesize);

or receive one less character

char *buffer1;
buffer1 =new char [filesize];
memset(buffer1, 0, filesize);
ifs.read(buffer1, filesize - 1);


Sure you are right, I missed that :blush:

Cheers

esselfe
May 26th, 2006, 07:30 PM
You're right, MessageBox is clean! That was a tricky one!
delete [] buffer1 was further in the code...