结构体二维数组如何写文件和读文件

bestman 2017-04-27 10:00:10
下面是我写的代码,总是出现段错误

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

typedef struct
{
int flag;
bool punched;
}item_info;

namespace Ui {
class Widget;
}

class Widget : public QWidget
{
Q_OBJECT

public:
explicit Widget(QWidget *parent = 0);
~Widget();
void init_func();

private:
Ui::Widget *ui;
item_info **p1_list;
item_info **p_list;

};

#endif // WIDGET_H


#include "widget.h"
#include "ui_widget.h"
#include <stdio.h>
#include <QDebug>

Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
init_func();
}

Widget::~Widget()
{
// delete p_list;
// delete p1_list;
delete ui;
}

void Widget::init_func()
{
int rows = 8;
int columns = 12;

p1_list = new item_info*[rows];
p_list = new item_info*[rows];
for (int i = 0; i < rows; i++)
{
p1_list[i] = new item_info[columns];
p_list[i] = new item_info[columns];
}

for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
p1_list[i][j].flag = j;
p_list[i][j].flag = 0;
p1_list[i][j].punched = false;
p_list[i][j].punched = false;
}
}
FILE *fp = fopen("./table1", "rb+");
if (fp)
{
qDebug() << fwrite(&p1_list, sizeof(item_info), 96, fp);
fseek(fp, 0, SEEK_SET);
qDebug() << fread(&p_list, sizeof(item_info), 96, fp);
}
fclose(fp);

for (int i = 0; i < rows; i++)
{
for (int j = 0; j < columns; j++)
{
qDebug() << "(" << i << j << ")" << p_list[i][j].flag;
}
}
return;
}
...全文
229 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Little柯南 2017-10-25
  • 打赏
  • 举报
回复
用容器Qtl
bestman 2017-04-27
  • 打赏
  • 举报
回复
C语言该如何写?
bestman 2017-04-27
  • 打赏
  • 举报
回复
中间的file.flush();改为file.seek(0);
bestman 2017-04-27
  • 打赏
  • 举报
回复
引用 3 楼 adeng1919 的回复:
当然不是,你好好看看

QFile file("./table1");

    bool ret = file.open(QIODevice::ReadWrite|QIODevice::Truncate);
    QDataStream out(&file);
    if (!ret)
    {
        qDebug() << "open table1 failed";
    }
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            out << p1_list[i][j].flag << p1_list[i][j].punched;
        }
    }
    file.flush();
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            out >> p_list[i][j].flag >> p_list[i][j].punched;
        }
    }

    file.close();
这么写岂不是很麻烦么?
懒懒的吉他手 2017-04-27
  • 打赏
  • 举报
回复
当然不是,你好好看看
bestman 2017-04-27
  • 打赏
  • 举报
回复
引用 1 楼 adeng1919 的回复:
都用Qt了,直接用QDataStream来读写二进制数据不是更简单,不用操心内存管理
我用的结构体,QDataStream只能写Qt指定的类型格式啊
懒懒的吉他手 2017-04-27
  • 打赏
  • 举报
回复
都用Qt了,直接用QDataStream来读写二进制数据不是更简单,不用操心内存管理

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧