C++ 文件的高速存储。5M只需0.003s

目前做一个项目需要高速存储下来。实测5M只需0.003s。我看了一下PCIE也是这种方式存储的。之前用QT的方式写文件,大概需要0.05s,还是c语言的写法快得多

unsigned char *p = new unsigned char[SIZE];

//对p进行赋值操作,但是有要求必须是无符号char类型的数据,如果不是需要自定义转换为8位+低8位,
//比如65535可以转换为高八位0XFF和低八位0XFF。具体怎么定义自己决定。最小单元必须为unsigned char类型的数据。

//5M 0.003s 这种方式是C语言存储,优点是速度快,缺点是写出的文件是ascii的字符形式,超过128的字符就成为乱码
//但是可通过程序转换
 Write(filePath,(char *)p,SIZE);
BOOL ReadThread::Write(QString filePath,char *buffer, DWORD contentLen)
{
    HANDLE pFile;
    char *tmpBuf;
    DWORD dwBytesWrite,dwBytesToWrite;

    pFile = CreateFile(filePath.toStdWString().data(),GENERIC_WRITE,
        0,
        NULL,
        CREATE_ALWAYS,        //总是创建文件
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if ( pFile == INVALID_HANDLE_VALUE)
    {
        printf("create file error!\n");
        CloseHandle(pFile);
        return FALSE;
    }

    dwBytesToWrite = contentLen;
    dwBytesWrite = 0;

    tmpBuf = buffer;

    do{                                       //循环写文件,确保完整的文件被写入

        WriteFile(pFile,tmpBuf,dwBytesToWrite,&dwBytesWrite,NULL);

        dwBytesToWrite -= dwBytesWrite;
        tmpBuf += dwBytesWrite;

        } while (dwBytesToWrite > 0);

    CloseHandle(pFile);

    return TRUE;
}

直接打开的话是一些问号???
在这里插入图片描述
在编码处选择UTF-8编码
在这里插入图片描述
有写就有读

BOOL MainWindow::ReadShow(QString filePath)
{
    HANDLE pFile;
    DWORD fileSize;
    unsigned char *buffer,*tmpBuf;
    DWORD dwBytesRead,dwBytesToRead,tmpLen;

    pFile = CreateFile(filePath.toStdWString().data(),GENERIC_READ,
        FILE_SHARE_READ,
        NULL,
        OPEN_EXISTING,        //打开已存在的文件
        FILE_ATTRIBUTE_NORMAL,
        NULL);

    if ( pFile == INVALID_HANDLE_VALUE)
    {
        printf("open file error!\n");
        CloseHandle(pFile);
        return FALSE;
    }

    fileSize = GetFileSize(pFile,NULL);          //得到文件的大小
    //qDebug() << fileSize;

    buffer = (unsigned char *) malloc(fileSize);
    ZeroMemory(buffer,fileSize);
    dwBytesToRead = fileSize;
    dwBytesRead = 0;
    tmpBuf = buffer;

    do{                                       //循环读文件,确保读出完整的文件

        ReadFile(pFile,tmpBuf,dwBytesToRead,&dwBytesRead,NULL);

        if (dwBytesRead == 0)
            break;

        dwBytesToRead -= dwBytesRead;
        tmpBuf += dwBytesRead;

        } while (dwBytesToRead > 0);

    CloseHandle(pFile);

    //  TODO 处理读到的数据 buffer
    QVector<float> fVec;

    //qDebug() <<  "read success";
    float number = 0.0;
    float value;

    for(int i=1;i<=fileSize;i=i+2)
    {
        number = (*(buffer+i))+(*(buffer+i-1)*256);
        //*********将所有数据都存下来*********
        fVec.push_back(value);
//接下来就自己对数据的处理
    }
    free(buffer);
    fVec.clear();

    return TRUE;
}

这是我自己处理后的显示
在这里插入图片描述
这是采集和存储的时间,这个是一个单独的线程 。读文件以及显示等在主线程中执行
在这里插入图片描述


版权声明:本文为zy47675676原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。