我日那些看不見的字符!!!
我折騰了2天艹
感謝:\u202a 神奇的控制字符 讓我知道了路徑不能隨便粘貼……
起因是這樣的,我想試一下qt的正則表達式截取文件內容,需要QFile取文件路徑,結果我習慣性地從文件屬性的安全裏找對象路徑(文件屬性->安全->對象名稱處複製)
然後我粘在了一個按鈕代碼上(正則表達式還沒用上呢)
void MainWindow::on_pushButton_clicked()
{
QString displayString;
std::string a="C:\\Users\\23216\\Desktop\\1.txt";//這是文件屬性粘的
// std::string a="C:\\Users\\23216\\Desktop\\1.txt";//這是手敲的
QFile file(QString::fromStdString(a));
qDebug()<<file.errorString();
qDebug()<<file.fileName();
if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
{
qDebug()<<"Can't open the file!"<<endl;
}
while(!file.atEnd())
{
QByteArray line = file.readLine();
QString str(line);
qDebug()<< str;
displayString.append(str);
}
}
結果輸出是這樣的,
在調試時發現前面總有一傳詭異字符,這樣路徑確實不對了
後來
我試了路徑符號,證實了"\\"
和"/"
是一樣的,只有“\”
是單純的轉義字符不正確。
再後來,我不斷地試驗函數
//QString::fromLocal8Bit() (曾經在Windows上路徑的問題這樣解決過)
QFile file(QString::fromLocal8Bit("C:\\Users\\23216\\Desktop\\1.txt"));
//string、QString::fromStdString(a)組合,試着去除怪異字符
string a ="C:\\Users\\23216\\Desktop\\1.txt"
QString::fromStdString(a)
但是這個字符陰魂不散……我各種搜索絕對路徑爲什麼不管用……證實方向錯誤是致命的,他會讓你緣木求魚。
再再後來索性直接搜索調試時路徑上的奇怪字符
\u202a 神奇的控制字符
再後來手敲了一遍……就成了…………
這讓我有了信心——一般來說引用絕對路徑的函數不會出錯,除非路徑出錯。