我要编辑一个文件的内容。我正在使用 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
字节。
在这种特定情况下,您需要 peek和 seek方法。您还需要使用 QIODevice::Append | 打开
flags QFile
QIODevice::读写
关于c++ - 从 QFile 获取 QByteArray 并将其写入同一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36441885/