qt 多个字符串 序列化到文件注意事项。

来源:互联网 发布:网络传输文件软件 编辑:程序博客网 时间:2024/05/20 22:27

当多个字符串 序列化到文件是,每个字符串尾要加endl。 用来区分该字符串尾部。

否则输入时会区分不了各个字符串。 见下例:

#include <QtGui>


#define CLIPFILE "clip.txt"
QString commonStr[4];  //commonStr[0] 本测试程序未使用
QString str[4];            //str[0] 本测试程序未使用

int main(int argc, char *argv[])
{
    (void) argc;
    (void) argv;
    commonStr[1]="1";
    commonStr[2]="2";
    commonStr[3]="3";
    //持久化到flash, 实际上是文件操作
    QFile outFile(CLIPFILE);
    outFile.open(QIODevice::WriteOnly|QIODevice::Text);
    QTextStream ts(&outFile);
    for(int i=1;i<4;i++)
    {
        ts << commonStr[i]<<endl;
//        ts << commonStr[i];  //如果不加endl, 读入时会直接读到文件尾给第一个字符串
    }
    outFile.close();
    int r=system("sync");
    (void) r;


    QFile file(CLIPFILE);
    if(!file.exists()) return 0;
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QTextStream ts2(&file);
    for(int i=1;i<4;i++)
        ts2>>str[i];
    file.close();
    qDebug()<<str[1]<<endl;
    qDebug()<<str[2]<<endl;
    qDebug()<<str[3]<<endl;

    return 0;
}

/*
//加endl 后正确的打印输出
./qttest
"1"
"2"
"3"
//查看clip.txt 二进制文件,字符串之间已用0x0a隔开
$ xxd clip.txt
0000000: 310a 320a 330a                           1.2.3.

//不加endl 错误的打印输出
./qttest
"123"
""
""
//查看clip.txt 二进制文件, 多个字符串被连接在了一起。不是我们所需要的。
 $> xxd clip.txt
 0000000: 3132 33                                  123
*/


0 0
原创粉丝点击