1.C語言函數(shù)fopen(),式例代碼:
-
-
-
- #include <stdio.h>
- #include <tchar.h>
-
- int _tmain(int argc, _TCHAR* argv[])
- {
-
- FILE *pFile=_tfopen(_T("http://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("http://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,式例代碼:
-
-
-
- #include <tchar.h>
- #include <fstream>
- #include <string>
- #include <iostream>
- using namespace std;
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- fstream file;
-
- file.open("http://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("http://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類
-
-
-
- #include <tchar.h>
- #include <afx.h>
-
- int _tmain(int argc, _TCHAR* argv[])
- {
- CStdioFile cFile;
-
- if(!cFile.Open(_T("http://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("http://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中文輸出。
-
-
-
- #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)
- {
- 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;
- }