Qt寫文字檔案

2021-06-01 21:20:12 字數 1349 閱讀 4930

qtexststream用於讀寫純文字以及html,xml等文字格式的檔案,此類考慮了unicode編碼與系統本地編碼的或其它任意編碼之間的轉換問題,別且明確地處理了因使用不同的作業系統而導致的行尾符之間的轉換(windows系統的行尾符是「\r\n」,unix和mac os x系統是「\n」)。

qtexststream的操作物件是qiodevice,可是qfile,qtemporaryfile,qbuffer,qprocess,qtcpsocket或者qupdsocket,此外還可以直接在qstring上使用,如:

qstring str;

qtextstream(&str)fileoutfileout.setintegerbase(16);

檔案包含:

#include #include
**:

qfile file("test.txt");

if(!file.open(qiodevice::writeonly))

qtextstream fileout(&file);

// fileout.setcodec("utf-8"); //unicode utf-8 ansi

fileout <<"helloworld!"<<"\n";

fileout d′???t£?μú1dd.

使用上面的方式寫檔案時,如果檔案不存在,會自動建立。寫入英文時沒有問題,但是如果寫入中文,出現的是亂碼。

#include #include #include #include

**:qfile file("test.txt");

if(!file.open(qiodevice::writeonly | qfile::text))

qtextcodec* codec=qtextcodec::codecforname("utf-8");

std::string strdata="abcde寫入中文";

char* buf=new char[strdata.size()+1];

strcpy(buf,strdata.c_str());

qstring qstr=qstr.fromlocal8bit(buf); //fromlocal8bit是qstring的靜態成員方法,這裡的物件名只起標識類的作用

qtextstream out (&file);

out.setcodec(codec);

out 使用上面的方法可以輸出中文,但是過於複雜並且使用不方便。可以使用tr函式來簡化問題。

qt寫文字檔案換行符 Qt 文字檔案讀寫

文字檔案讀寫 二進位制檔案比較小巧,但是不是人可讀的格式。文字檔案是一種人可讀的格式的檔案,為了操作這種檔案,我們需要使用 qtextstream 類。qtextstream 和 qdatastream的使用類似,只不過它是操作純文字檔案的。還有一些文字格式,比如 xml html,雖然可以由 qt...

寫文字檔案

textoper 文字檔案操作類 public class textoper 新建乙個檔案 public bool createfile string strpath,string strname else file.create strpath strname return true catch ...

qt寫文字檔案換行符 Qt向文字檔案輸出換行

使用qtextstream向txt檔案輸出換行時,需要使用qiodevice text標誌。官方文件對qiodevice text的解釋 when reading,the end of line terminators are translated to n when writing,the end...