1.C语言函数fopen(),式例代码:
//author:firehood //data: 2011-5-19 #include <stdio.h> #include <tchar.h> int _tmain(int argc, _TCHAR* argv[]) { // 创建或打开二进制文件,并以追加方式打开 FILE *pFile=_tfopen(_T("//NAND2//FileLog1.txt"), _T("wab+")); if(pFile) { fwprintf(pFile, _T("%s/n"), _T("test1")); fwprintf(pFile, _T("%s/n"), _T("test2")); fwprintf(pFile, _T("%s/n"), _T("test3")); fclose(pFile); } // 读文件 pFile=_tfopen(_T("//NAND2//FileLog1.txt"), _T("rb")); TCHAR str[20]; if(pFile) { while(_ftscanf(pFile,_T("%s/n"),str)!=EOF) { _tprintf(_T("%s/n"),str); } fclose(pFile); } return 0; }
2.C++ fstream,式例代码:
//author:firehood //data: 2011-5-19 #include <tchar.h> #include <fstream> #include <string> #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { fstream file; // 以追加方式打开文件,只写操作 file.open("//NAND2//FileLog.txt", ios_base::out | ios_base::app); if(file.is_open()) { file << "test1" << endl; file << "test2" << endl; file << "test3" << endl; file.flush(); file.close(); } // 以只读方式打开文件 file.open("//NAND2//FileLog.txt", ios_base::in); if(!file.is_open()) { cout << "Open file failed"<<endl; exit (1); } string str; while (!file.eof()) { // 获取一行数据 getline(file,str); cout << str.c_str() << endl; } file.close(); return 0; }
3.mfc CFile、CStdioFile类
//author:firehood //data: 2011-5-19 #include <tchar.h> #include <afx.h> int _tmain(int argc, _TCHAR* argv[]) { CStdioFile cFile; // 写文件 if(!cFile.Open(_T("//NAND2//FileLog2.txt"),CFile::modeCreate | CFile::modeWrite | CFile::typeBinary)) { printf("Create file failed../n"); return false; } cFile.WriteString(L"test1"); cFile.WriteString(L"test2"); cFile.WriteString(L"test3"); cFile.Close(); // 读文件 if(!cFile.Open(_T("//NAND2//FileLog2.txt"),CFile::modeRead | CFile::typeBinary)) { printf("Open file failed../n"); return false; } CString str; while(cFile.ReadString(str)) { // 输出 _tprintf(_T("%s/n"),str); } cFile.Close(); return 0; }
CFile 写文件操作示例,支持ANSI、UNICODE中文输出。
//author:firehood //data: 2011-5-19 #include <tchar.h> #include <afx.h> int _tmain(int argc, _TCHAR* argv[]) { CFile cFile; if(cFile.Open(_T("D://FileLog3.txt"),CFile::shareExclusive|CFile::modeCreate|CFile::modeWrite)) { #ifdef _UNICODE ULONGLONG dwFileLen = cFile.GetLength(); if (0 == dwFileLen) // 文件为空时写入UNICODE字节序标记 { const unsigned char LeadBytes[] = {0xff, 0xfe}; cFile.Write(LeadBytes, sizeof(LeadBytes)); } #endif TCHAR *str=_T("中文字符串"); cFile.Write(str,_tcslen(str)*sizeof(TCHAR)); cFile.Close(); } else { printf("Create file failed/n"); } return 0; }