16,240
社区成员
发帖
与我相关
我的任务
分享
QFile Temp_Read ( "C:/Users/Dell/Desktop/Qt/File_Out/Temp" ) ;
if( !Temp_Read.open( QIODevice::ReadOnly ) )
{
qDebug()<< "文件 Temp 无法被打开!"<<endl ;
}
char *a = (char*)malloc( sizeof(char)*10 ) ;
int i = 0 ;
QTextStream In ( &Temp_Read ) ; // 实际上 这种方法 是错误的,他不向 C++ 一样 , 可以不考虑换行的问题,Qt读取的是字符串
// 在读取字符串之后需要进行字符串的解析。
QString Line ;
QByteArray Temp_Arr ;
// 读取的参数
char top [2] ;
int weight , height , big ;
while( i < 3 )
{
if( 0 == i ) // 当 i = 0 的时候,读取第一行 top[0] , top[1]
{
In.seek( i ) ;
Line = In.readLine();
Line = Line.simplified() ;
Temp_Arr = Line.toLatin1() ;
a = Temp_Arr.data() ;
top[0] = a[0] ;
top[1] = a[1] ;
qDebug() << "top[0] = " << top[0] << endl << "top[1] = " << top[1] << endl ;
}
if( 1 == i ) // 当 i=1 的时候,读取第二行 wieght , height
{
In.seek( i ) ;
Line = In.readLine() ;
QStringList Str_List = Line.split( " " ) ;
Str_List[0] = Str_List[0].simplified() ;
weight = Str_List[0].toInt() ;
Str_List[1] = Str_List[1].simplified() ;
height = Str_List[1].toInt() ;
qDebug() << "Weigth = " << weight << "Height = " << height << endl ;
}
if( 2 == i ) // 当 i=2 的时候,读取第三行 big
{
In.seek( i ) ;
Line = In.readLine() ;
QStringList Str_List = Line.split( " " ) ;
Str_List[0] = Str_List[0].simplified() ;
big = Str_List[0].toInt() ;
qDebug() << "big = " << big << endl ;
}
i++ ;
}
Temp_Read.close();
free( a ) ;
我写过这样写,但是结果是错的,把 5 读成了int 类型。往后的结果就读错了!
void MainWindow::openFileForTest()
{
QString fileName=QFileDialog::getOpenFileName(this, tr("Open File"),
"D:\\Qt\\projects",
tr("Texts (*.txt)"));
QFile openedFile(fileName);
if (openedFile.open(QIODevice::ReadOnly|QIODevice::Text) == false)
{
QMessageBox::warning(this,"warning", QString("File (%1) open failed").arg(fileName));
return;
}
QTextStream out(&openedFile);
while(!out.atEnd())
{
ui->plainTextEdit->appendPlainText( out.readLine() );
}
openedFile.close();
}
QString a; int i1, i2, i3; in >> a >> i1 >> i2 >> i3; 就搞定了吧, 你写的这么麻烦 是什么意思?
应该是你哪里写越界了,这个函数是不会出问题的。