当前位置:   article > 正文

解析txt文件,赋值结构体数组_qt读取文件数据并赋值给变量

qt读取文件数据并赋值给变量

qt可以利用自己的库来解析txt文件,赋值到数组中供程序使用,代码如下

首先定义一个数组,比如

  1. struct s_write_file {
  2. QByteArray * ptr_file;
  3. QString name;
  4. QString city;
  5. unsigned int age;
  6. };

在程序中

  1. unsigned int all_count = 0;
  2. s_write_file w_file[32];
 

  1. void Widget::ReadFile()
  2. {
  3. QFile fileRead("/mnt/info.txt");
  4. fileRead.open(QFile::ReadOnly | QFile::Text);
  5. QTextStream in(&fileRead);
  6. QString strContent="";
  7. int file_num= 0;
  8. while(!in.atEnd())
  9. {
  10. strContent += in.readLine();
  11. file_num++;
  12. }
  13. fileRead.flush();
  14. fileRead.close();
  15. // s_write_file w_file[W_FILE_NUM]; //此处可以判断txt的行数来判断数组的参数个数,不需要直接开w_file[32]
  16. QStringList strlist = strContent.split(";"); //利用;来间隔
  17. for(int i=0;i<strlist.count();i++)
  18. {
  19. QStringList strstrlist=strlist.at(i).split("#");//利用#来间隔
  20. for(int j=0;j<strstrlist.count();)
  21. {
  22. QString file = strstrlist.at(j++).toLocal8Bit().data();
  23. QString md5 = strstrlist.at(j++).toLocal8Bit().data();
  24. QString age_String =strstrlist.at(j++).toLocal8Bit().data();
  25. int age = age_String.toInt(0,10); //10进制计数
  26. w_file[all_count].ptr_file = NULL;
  27. w_file[all_count].name = file;
  28. //qDebug() << w_file[all_count].name;
  29. w_file[all_count].city = city;
  30. //qDebug() << w_file[all_count].city;
  31. w_file[all_count].age= age;
  32. //qDebug() << w_file[all_count].age; all_count++;
  33. }
  34. }
  35. }



具体的txt文件如下
  1. wangxiaohong#beijing#20;
  2. zhangxiaolei#shanghai#16;
  3. huxiaohei#guangzhou#25;
  4. lixiaoming#shanxi#32;
  5. huangxiaohu#zhejiang#29;
  6. zhaoxiaoling#chongqing#26


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/730763
推荐阅读
相关标签
  

闽ICP备14008679号