Qt入門-ファイル読み書き


バイナリファイルの読み書きファイルはQFileクラス、QStreamを使用できます
テキストファイルの読み書きはQTextStreamクラスを使用することをお勧めします.ファイルの操作が便利です.
ファイルを開くには、パラメータでファイルを開くモードを指定する必要があります.
Constant		Value	Description
QIODevice::NotOpen	0x0000	The device is not open.
QIODevice::ReadOnly	0x0001	The device is open for reading.
QIODevice::WriteOnly	0x0002	The device is open for writing.
QIODevice::ReadWrite	ReadOnly | WriteOnly	The device is open for reading and writing.
QIODevice::Append	0x0004	The device is opened in append mode, so that all data is written to the end of the file.
QIODevice::Truncate	0x0008	If possible, the device is truncated before it is opened. All earlier contents of the device are lost.
QIODevice::Text	0x0010	When reading, the end-of-line terminators are translated to '
'. When writing, the end-of-line terminators are translated to the local encoding, for example '\r
' for Win32. QIODevice::Unbuffered 0x0020 Any buffer in the device is bypassed.

QIODevice::Textはテキストファイルを読み書きするときに使用し、改行をローカル改行に自動的に変換できます.
(1)テキストファイルへの書き込み
	QFile f("c:\\test.txt");
	if(!f.open(QIODevice::WriteOnly | QIODevice::Text))
	{
		cout << "Open failed." << endl;
		return -1;
	}

	QTextStream txtOutput(&f);
	QString s1("123");
	quint32 n1(123);

	txtOutput << s1 << endl;
	txtOutput << n1 << endl;

	f.close();

書き込みファイルの内容は次のとおりです.
123
123
(2)テキストファイルを読み込む
	QFile f("c:\\test.txt");
	if(!f.open(QIODevice::ReadOnly | QIODevice::Text))
	{
		cout << "Open failed." << endl;
		return -1;
	}

	QTextStream txtInput(&f);
	QString lineStr;
	while(!txtInput.atEnd())
	{
		lineStr = txtInput.readLine();
		cout << lineStr << endl;
	}

	f.close();

マスク印刷の内容は次のとおりです.
123
123