«

»

Jun 03 2010

Leer y escribir archivos binarios usando QDataStream

Este post es muy similar al anterior sólo que el archivo no contiene texto, mas bien es una serie de registros con PDT’s (Primitive Data Types), lo cual puede servir para tener una idea, para el manejo datos binarios en archivos.

En este caso, la clase a utilizada es QDataStream.

#include <QFile>
#include <QDataStream>
#include <QDebug>

#define string_length 20

//a structure to set the information with some pdt's
struct dummy_struct
{

	int i;
	char c;
	bool b;
	float f;
	char s[string_length];
	//for convenience
	void set(int i, char c, bool b, float f, const char s[])
	{
		this->i = i;
		this->c = c;
		this->b = b;
		this->f = f;
		for (int j = 0; j < string_length; j++)
			this->s[j] = s[j];
	}
};

int main(int argc, char *argv[])
{
	//to avoid warnings.
	Q_UNUSED(argc);
	Q_UNUSED(argv);

	dummy_struct d;

	//Open the file for writing, and set the data stream to write, to the file.
	QFile file_for_writing("file.dat");
	file_for_writing.open(QIODevice::WriteOnly);
	QDataStream stream_for_writing(&file_for_writing);

	//set/write the first record
	d.set(102, 'A', true, 157.63, "First Record");
	stream_for_writing.writeRawData(reinterpret_cast<char *>(&d), sizeof(d));

	//set/write the second record
	d.set(235, 'M', false, 290.26, "Second Record");
	stream_for_writing.writeRawData(reinterpret_cast<char *>(&d), sizeof(d));

	//set/write the third record
	d.set(347, 'z', true, 385.48, "Third Record");
	stream_for_writing.writeRawData(reinterpret_cast<char *>(&d), sizeof(d));

	//close the file
	file_for_writing.close();

	//Open the file for reading, and set the data stream to read from the file.
	QFile file_for_reading("file.dat");
	file_for_reading.open(QIODevice::ReadOnly);
	QDataStream stream_for_reading(&file_for_reading);

	//read and prints the first record.
	stream_for_reading.readRawData(reinterpret_cast<char *>(&d), sizeof(d));
	qDebug() << d.i << " " << d.c << " " << d.b << " " << d.f << " " << d.s;

	//reads and prints the second record.
	stream_for_reading.readRawData(reinterpret_cast<char *>(&d), sizeof(d));
	qDebug() << d.i << " " << d.c << " " << d.b << " " << d.f << " " << d.s;

	//reads and prints the third record.
	stream_for_reading.readRawData(reinterpret_cast<char *>(&d), sizeof(d));
	qDebug() << d.i << " " << d.c << " " << d.b << " " << d.f << " " << d.s;

	//close the file
	file_for_reading.close();
}

Código fuente

Relacionado

About the author

Ni pena Ni gloria

Actualmente soy lo que soy, más cerca de lo que seré; y cada vez más lejos de lo que fuí.

6 comments

  1. Fausto Andres

    Hola….
    Mi iquietud es acerca de el manejo de QDataStream pero no con estructuras (struct), si no, con clases (class).

    Tengo un problema con el manejo de archivos binarios y clases.

    si me puedes ayudar, muchas gracias

  2. Lex

    Hola.

    Cual será el problema?

    El uso de un struct para este tipo de operaciones es casi una forma clasica de realizarlo, ya sea en c, c++ o utilizando c++ con algun framework, en este caso Qt. Sin embargo, como todo en c y c++, es solo cuestión de experimentar un poco. Con respecto a las clases, estas, por supuesto, constituyen una estructura muy diferente a un struct.

    He notado, la tendencia a evitar struct y algunas estructuras, cuando se programa con c++, porque no parecen seguir el paradigma OO, en realidad esto no provocará ningun tipo de problema.

  3. Lucas

    Hola,

    Yo lo que necesito es leer el contenido de un archivo binario que contiene 10 bytes dejando el contenido en un QByteArray para verificar el valor un byte en particular. No puedo leerlo como texto porque no son caracteres visibles y hay 0x00s entre medio.

    Hace unos meses lo logre despues de 1 dia cuando necesitaba calcular el CRC32 de un archivo pero ahora no logro hacerlo y no encuentro mi codigo :S.

    1. Ni pena Ni gloria

      Hola.

      Pues no he podido probar, pero si te fijas en la documentación del QByteArray puedes ayudarte con el contructor QByteArray ( const char * data, int size ). Yo empezaría por ahí.

      Saludos.

      1. Lucas

        Gracias por contestas, al final recorde que lo ttermine haciendo con un buffer comun porque por mas que intente con el data y data_ptr del QByte Array me daba problemas.


        QFile file("/tmp/archivo");
        if (file.open(QFile::ReadOnly))
        {
        char buf[1024];
        QDataStream Stream(&file);
        qint64 lineLength = Stream.readRawData(buf, 5);
        if (lineLength != -1)
        {
        qDebug()<<GetHexa(buf[0]);
        qDebug()<<GetHexa(buf[1]);
        qDebug()<<GetHexa(buf[2]);
        qDebug()<<GetHexa(buf[3]);
        qDebug()<<GetHexa(buf[4]);
        // the line is available in buf
        }
        }
        file.close();

        GetHexa me devuelve un string con el Hexadecimal del byte para debug.

        1. Ni pena Ni gloria

          Me alegro que hayas podido solucionar tu problema. Y gracias por compartir el código que utilizaste.
          :)

Leave a Reply

Your email address will not be published.


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Switch to mobile version