c++ - 从 QFile 获取 QByteArray 并将其写入同一个文件

标签 c++ qt qbytearray

我要编辑一个文件的内容。我正在使用 QFile 处理文件。现在,我想以 1024 字节的小块读取它。到目前为止,我做到了:

QFile file("~/samplefile");

long long sizeoffile = file.size();

size = size/1024;          ///*this is for loop size devoid by 1024 because I want to run loop filesize/1024  because in each cycle I read 1024 bytes **///
QString contentsToBeErased = "sample";

QString eraser = contentsToBeErased;

eraser = eraser.fill('*');

int pos = 0;               ////** This is the position of  'contentsToBeErased' in 1024 bytes(for each cycle)  **//

QByteArray myByteArray;

if(!file.open(QIODevice::ReadWrite | QIODevice::Text))
return;
for(long long i =0; i<size; i++)
{
  myByteArray = file.readLine(1025);   ////**1025 is used bcoz readline reads 1 less bytes**//

  int sizeArray = 0;

  QTextCodec *byteArraytoString = QTextCodec::codecForName("UTF-8");     //conevrting bytearray to string

  QString thisString = byteArraytoString->toUnicode(rohitarray);

    if(thisString.contains(contenttobeerased, Qt::CaseInsensitive))
        {
           int occurrence = thisString.count(contentsToBeErased,Qt::CaseInsensitive);
           for(int ii = 0; ii<occurrence; ii++)
            {
                pos = thisString.indexOf(contentsToBeErased, pos,Qt::CaseInsensitive);
                thisString.replace(pos,contentsToBeErased.size(), erase);
                pos = pos + contentsToBeErased.size() ;
            }

             myByteArray = thisString.toUtf8();
             sizeArray = myByteArray.length();
             QFile file1("~/samplefile");
             file1.open(QIODevice::WriteOnly);
             file1.write(myByteArray);
             file1.close();
          }
}

第一次尝试时效果很好,但在第二次尝试中,我无法使用 readLine(1025); 读取接下来的 1024 个字节。它再次读取前 1024 个字节。

所以我的第一个问题是我不知道如何增加 readLine(); 的位置来获取接下来的 1024 个字节。

第二个问题是我不知道如何在写入第一个字节数组后将第二个字节数组write() 写入文件,因为如果我只使用write(),它将用下一个字节数组替换前一个字节数组。那么如何在文件末尾追加数组呢?

最佳答案

首先阅读文档。 QIODevice::readLine(qint64 maxSize = 0)读取直到遇到换行符 ("\n") 或 maxSize 字节。

在这种特定情况下,您需要 peekseek方法。您还需要使用 QIODevice::Append | 打开 QFile QIODevice::读写 flags

关于c++ - 从 QFile 获取 QByteArray 并将其写入同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36441885/

相关文章:

c++ - 将 OpenGL 转换为 PNG

c++ - 在 QTreeView 中维护 checkedstatus 继承

c++ - 有没有一种安全的方法可以同时使用 C++11 智能指针和原始指针接口(interface)?

python - QFileDialog 为所有支持的图像格式创建过滤器

c++ - 从字节数组加载图像到图形 View

c++ - 如何从对象 std::tuple<Head,Tail...> 获取对元组尾部的引用

c++ - 通过 C++ 提供登录名和密码,就像 Unix/Linux 中的 expect 脚本

c++ - 如何将 std::vector<uint8_t> 转换为 QByteArray?

c++ - 对于(自动指针 : vectorOfPointers) vs for(auto pointer : vectorOfPointers)

c++ - 使用 QT 和 SQLite 通过单元格编辑更新数据库