PDA

View Full Version : Writing data in char pointer using QFile



ehnuh
18th October 2012, 08:53
Hi , I am having problems in writing data in a file. I have a file that contains binary code . This will serve as a dummy file that QFile will read and display in the GUI. So far, reading the data and displaying it has no issues.

WHen try to write it into the same file, the file becomes blank.( Basically the contents are erased even if I used the same char pointer. I used debug mode and checked the contents of the char pointer. The data was still there but nothing was written on the file.

here is sample code of writing:

void DisplaySize::write_bin_file(unsigned long datasize, unsigned char *dataPtr, QString directory)
{

QFile DummyFile(directory);

if(!DummyFile.open(QIODevice::WriteOnly | QIODevice::Text))
return;

QByteArray testing= "asfdsfd";
unsigned char *newPtr = NULL;
newPtr = (unsigned char *)malloc(datasize);
memcpy(newPtr ,dataPtr,datasize);



DummyFile.write((const char*)newPtr );




DummyFile.close();
}



the Qbytearray testing is just to test whether I can write on the text file. If I used that, and use testing.constData() to get the char* pointer, it writes on the file.

Lesiok
18th October 2012, 10:52
Try :
DummyFile.write((const char*)newPtr,datasize );
Read in Qt doc what is difference.

ChrisW67
19th October 2012, 02:13
You certainly do not want to open the file with the QIODevice::Text flag: it will mangle carriage returns and line feeds in your binary data on Windows.

Why bother with all the copying and leaking memory? You have a pointer to the data and a data length... QIODevice::write() has a variant to fit. The whole function comes down to:


void write_bin_file(unsigned long datasize, unsigned char *dataPtr, QString directory)
{
QFile DummyFile(directory);

if(DummyFile.open(QIODevice::WriteOnly)) {
qint64 bytesWritten = DummyFile.write(reinterpret_cast<const char*>(dataPtr), datasize);
if (bytesWritten < datasize) {
// error
}
DummyFile.close();
}
}