QFile和QDataStream无法对文本读取
我建立了一个小实验,测试是否能够通过QFile和QDataStream来tokenize文本的内容。但是测试失败。我这里有一个文本内容是这样的:
TestFile.txt---------
abc def ghi
我想输出的结果是这样的:abcdefghi
源文件是这样的…………
#include <iostream>
#include <QFile>
#include <QDataStream>
#include <QString>
int main( int argc, char** argv )
{
using namespace std;
QFile file;
file.setFileName( "TestFile.txt" );
if ( !file.open( QIODevice::ReadOnly ) )
cout << "无法打开文件。\n";
cout << "打开文件成功!准备输出数据。\n";
QDataStream in( &file );
QString checkStr;
do
{
in >> checkStr;
cout << (char*)checkStr.data( );
}
while ( !checkStr.isEmpty( ) );
file.close( );
return 0;
}
但是程序无法去掉空格将文件的内容逐一输出。我改怎么做才能达到效果呢?
[最优解释]
trim一下不好么?
如果你是2进制文件用datastream比较好,文本文件textstream比较好。
如果你知道文件格式。使用文件偏移量直接读取,用datastream + readRawData.方法比较好。
大家还有啥其他经验和方法跟帖哈。
[其他解释]
QDataStream是二进制读写,QTextStream才是文本读写用的。
用QString::replace(" ", "");将空格替换掉,就成一串了。
[其他解释]
遍历一下QString中的字符如果满足bool QChar::isSpace () const这个就把它移除
[其他解释]
你这属于QString 的问题...
QString str = "abc def hijk";
int len = str.length();
int i=0;
for(i; i<len; i++)
{
if(str.at(i).isSpace())
str.remove(i,1);
}
qDebug()<<str;
[其他解释]
你们能不能测试一下呢?感觉你们讲的不对。
这个代码在我的机子上显示空的标签。TestFile.txt内容:abc def ghi
#include <QApplication>
#include <QLabel>
#include <QFile>
#include <QDataStream>
#include <QString>
int main( int argc, char** argv )
{
QApplication app( argc, argv );
QFile file( "TestFile.txt" );
QString showStr( "Empty String." );
QLabel showLabel;
if ( !file.open( QIODevice::ReadOnly ) )
{
showStr = "Can't open file.";
}
QDataStream in( &file );
in >> showStr;
file.close( );
showLabel.setText( showStr );
showLabel.setWindowTitle( "Experimental" );
showLabel.setFixedSize( 200, 50 );
showLabel.show( );
return app.exec( );
}
[其他解释]
文本文件为啥不用readline呢。。
[其他解释]
假设一行有很多空格呢?其实用标准C++可以做到的:
请看TestFile.txt:
abc def ghi
请看源程序:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
cout << "这是一个对比实验,可验证C++的文件流可以做到。\n";
fstream in( "TestFile.txt", ios::in );
if ( !in )
{
cout << "无法打开TestFile.txt。";
}
else
{
string showStr;
do
{
in >> showStr;
cout << showStr;
}
while ( !in.eof( ) );
in.close( );
}
return 0;
}
请看结果:
这是一个对比实验,可验证C++的文件流可以做到。
abcdefghighi
[其他解释]
谢谢提醒,你以上的回答都不靠谱。
修改后的代码是这样的,我开始编写的代码也有些错误:
#include <iostream>
#include <QFile>
#include <QTextStream>
#include <QString>
int main( int argc, char** argv )
{
using namespace std;
QFile file;
file.setFileName( "TestFile.txt" );
if ( !file.open( QIODevice::ReadOnly ) )
cout << "无法打开文件。\n";
cout << "打开文件成功!准备输出数据。\n";
//QDataStream in( &file );
QTextStream in( &file );
QString checkStr;
do
{
in >> checkStr;
cout << checkStr.toAscii().constData( );
}
while ( !checkStr.isEmpty( ) );
file.close( );
return 0;
}
可以达到和标准C++中fstream一样的效果。
[其他解释]
该回复于2012-10-23 13:22:05被版主删除
[其他解释]
那请问你的问题是数据没有读出来呢,还是读出来的内容显示的不对??
请把问题说的仔细些,大家才会明白,问题才会解决!
[其他解释]
你以前说的方法繁琐了点,要将很多的字节都读入一个字符串再去空格……我的想法是tokenize这些串,就像C编译器编译源文件词法分析一样的。而且我想要的效果都给你看了,真是的。
[其他解释]
这段程序没测试过吧?
肯定会运行错误。
[其他解释]
谁告诉你没测试过??回答问题请用点心,请告诉我哪里会运行错误了??