qt鎬庝箞鍒犻櫎鏂囦欢涓殑閮ㄥ垎鍐呭
鍦≦t涓紝瑕佸垹闄ゆ枃浠朵腑鐨勯儴鍒嗗唴瀹癸紝鍙互浣跨敤浠ヤ笅姝ラ锛?/p>
- 浣跨敤
QFile
绫绘墦寮€瑕佽繘琛屾搷浣滅殑鏂囦欢銆備緥濡傦紝鍋囪瑕佹搷浣滅殑鏂囦欢鍚嶄负file.txt
锛屽彲浠ヤ娇鐢ㄤ互涓嬩唬鐮佸垱寤轰竴涓?code>QFile瀵硅薄骞舵墦寮€璇ユ枃浠讹細
QFile file("file.txt");
if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
qDebug() << "Failed to open file";
return;
}
- 浣跨敤
QTextStream
绫昏鍙栨枃浠跺唴瀹广€?code>QTextStream绫绘彁渚涗簡鏂逛究鐨勬柟寮忔潵璇诲彇鍜屽啓鍏ユ枃浠剁殑鏂囨湰鍐呭銆傚彲浠ヤ娇鐢ㄤ互涓嬩唬鐮佸垱寤轰竴涓?code>QTextStream瀵硅薄锛屽苟浣跨敤瀹冩潵璇诲彇鏂囦欢涓殑鍐呭锛?/li>
QTextStream in(&file);
QString fileContent = in.readAll();
- 瀵硅鍒犻櫎鐨勯儴鍒嗗唴瀹硅繘琛屽鐞嗐€傛牴鎹渶瑕侊紝鍙互浣跨敤QString鐨勫嚱鏁版潵鍒犻櫎鏂囦欢鍐呭鐨勪竴閮ㄥ垎銆備緥濡傦紝鍙互浣跨敤
remove
鍑芥暟鍒犻櫎鎸囧畾浣嶇疆鐨勫瓧绗︼細
int startIndex = 5;
int count = 10;
fileContent.remove(startIndex, count);
- 鏇存柊鏂囦欢鍐呭銆備娇鐢?code>QTextStream绫荤殑
seek
鍑芥暟灏嗘枃浠舵寚閽堢Щ鍔ㄥ埌鏂囦欢寮€澶达紝骞朵娇鐢?code>QTextStream绫荤殑<<
鎿嶄綔绗﹀皢鏇存柊鍚庣殑鍐呭鍐欏洖鏂囦欢涓細
file.seek(0);
QTextStream out(&file);
out << fileContent;
- 鍏抽棴鏂囦欢銆備娇鐢?code>QFile绫荤殑
close
鍑芥暟鍏抽棴鏂囦欢锛?/li>
file.close();
瀹屾暣鐨勭ず渚嬩唬鐮佸涓嬫墍绀猴細
#include <QFile>
#include <QTextStream>
#include <QDebug>
int main()
{
QFile file("file.txt");
if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
qDebug() << "Failed to open file";
return 1;
}
QTextStream in(&file);
QString fileContent = in.readAll();
int startIndex = 5;
int count = 10;
fileContent.remove(startIndex, count);
file.seek(0);
QTextStream out(&file);
out << fileContent;
file.close();
return 0;
}
璇锋牴鎹疄闄呴渶姹備慨鏀规枃浠跺悕銆佸垹闄ょ殑璧峰浣嶇疆鍜岃鍒犻櫎鐨勫瓧绗︽暟绛夊弬鏁般€?/p>