文件操作

1.文件的讀取與寫入

新建一個MFC單文檔應用程序(工程名取:File),打開菜單資源新建一個文件菜單,並在其下添加以下菜單項(ID:IDM_FILE_READ,Caption:讀取)(ID:IDM_FILE_WRITE,Caption:寫入),並分別給它們添加CFileView類上的命令響應,編輯:

void CFileView::OnFileRead()  

    // TODO: Add your command handler code here 
    FILE *pFile=fopen("1.txt","r");//
爲了讀取而打開一個文件 
//    char ch[100]; 
//    memset(ch,0,100); 
    //
將字符數組中所有的數據都設爲零,這樣讀取時,就只讀取到有字符的位置 
//    fread(ch,1,100,pFile);//
讀取文件 
//    MessageBox(ch); 
    char *pBuf; 
    fseek(pFile,0,SEEK_END);//
將文件的指針移到文件的末尾 
    int len=ftell(pFile);//
獲取文件的大小 
    pBuf=new char[len+1];//
根據文件的大小分配內存,多分配一個是爲了存取'/0' 
    rewind(pFile);//
這個函數可以將文件指針移到文件的開始處 
    fread(pBuf,1,len,pFile);//
讀取len所表示的文件的長度的數據 
    pBuf[len]=0;//
將數組的最後個元素設置爲0,因爲數據索引是從0開始的,所以len表示最後一個 
    MessageBox(pBuf); 
    fclose(pFile); 
    //fflush(pFile);//
刷新緩衝區,讓緩衝區的數據寫入文件 

 
void CFileView::OnFileWrite()  

    // TODO: Add your command handler code here 
    FILE *pFile=fopen("1.txt","w");//
爲了寫入而打開一個文件 
    fwrite("http://www.baidu.com",1,strlen("http://www.baidu.com"),pFile); 
    //
把字符串寫入文件 
    //fwrite("http://www.baidu.com",1,strlen("http://www.baidu.com")+1,pFile); 
    //
爲了讓讀取到指定字符就結束,+1是在文件中多寫入一個字節,多寫的字節爲空,默認也是0,就是字符串的結尾 
    //fwrite("http://www.baidu.com",1,strlen("http://www.baidu.com"),pFile); 
    //
還可以再次寫入,位置是上次寫入後文件指針所在的位置 
 
    //fseek(pFile,0,SEEK_SET);//
將文件的指針位置設爲零 
 
    //fwrite("ftp://10.6.17.19",1,strlen("ftp://10.6.17.19"),pFile); 
    //fclose(pFile);//
關閉文件,表明文件的寫操作已完成,緩衝區內容將寫入文件 
    fflush(pFile);//
刷新緩衝區,讓緩衝區的數據寫入文件 
}

 

2.文件寫入時經常會碰到的問題

void CFileView::OnFileWrite()  

    //FILE *pFile=fopen("2.txt","w"); 
    FILE *pFile=fopen("2.txt","wb"); 
    char ch[3]; 
    ch[0]='a'
    ch[1]=10;//10
實際上指換行符 
    ch[2]='b'
    fwrite(ch,1,3,pFile);//
寫入 
    fclose(pFile); 
    //
運行可以發現在文件裏寫入了4個字節,回車符13佔了兩個字節 
    //
轉換成十六制可以發現:
61 0D 0A 62        ;a..b 
 } 
 
void CFileView::OnFileRead()  

    //FILE *pFile=fopen("2.txt","r");//
缺省是按文本方式(t)打開 
    FILE *pFile=fopen("2.txt","rb");//
以二進制方式(b)打開 
    char ch[100]; 
    fread(ch,1,3,pFile);//
讀取文件 
    ch[3]=0
    MessageBox(ch); 
    fclose(pFile); 
    //
以文本方式寫入的文件 
    //
以文本方式打開文件用3個字節讀取發現仍然可以讀出來 
    //
以二進制方式用3個字符打開不能將b讀出,只能讀到61 0D 0A 
     //
以二進制方式寫入的文件 
    //
以二進制方式用3個字符打開能將b讀出 

}

二進制文件和文本文件

 

3.一個問題

98341,將這個整數保存到文件中,要求在以記事本程序打開文件時,顯示的是98341

void CFileView::OnFileWrite()  

    FILE *pFile=fopen("3.txt","w"); 
    int i=98341; 
  char ch[5]; 
/*  ch[0]=9+48;//
ASCII碼存進去 
    ch[1]=8+48
    ch[2]=3+48
    ch[3]=4+48
    ch[4]=1+48

*/

itoa(i,ch,10);
    //fwrite(&i,4,1,pFile); 
    fwrite(ch,1,5,pFile); 
    fclose(pFile);
 
 }

===============================================

fopen, _wfopen

Open a file.

FILE *fopen( const char *filename, const char *mode );

FILE *_wfopen( const wchar_t *filename, const wchar_t *mode );

Function

Required Header

Compatibility

fopen

 

ANSI, Win 95, Win NT 

_wfopen

or  

Win NT 

 

For additional compatibility information, see Compatibility in the Introduction.

Libraries

LIBC.LIB 

Single thread static library, retail version 

LIBCMT.LIB 

Multithread static library, retail version 

MSVCRT.LIB 

Import library for MSVCRT.DLL, retail version 

 

The c, n, and t mode options are Microsoft extensions for fopen and _fdopen and should not be used where ANSI portability is desired.

Return Value

Each of these functions returns a pointer to the open file. A null pointer value indicates an error.

Parameters

filename

Filename

mode

Type of access permitted

Remarks

The fopen function opens the file specified by filename. _wfopen is a wide-character version of fopen; the arguments to _wfopen are wide-character strings. _wfopen and fopen behave identically otherwise.

Generic-Text Routine Mappings

TCHAR.H Routine

_UNICODE & _MBCS Not Defined

_MBCS Defined

_UNICODE Defined

_tfopen 

fopen 

fopen 

_wfopen 

 

The character string mode specifies the type of access requested for the file, as follows:

"r"

Opens for reading. If the file does not exist or cannot be found, the fopen call fails.

"w"

Opens an empty file for writing. If the given file exists, its contents are destroyed.

"a"

Opens for writing at the end of the file (appending) without removing the EOF marker before writing new data to the file; creates the file first if it doesn't exist.

"r+"

Opens for both reading and writing. (The file must exist.)

"w+"

Opens an empty file for both reading and writing. If the given file exists, its contents are destroyed.

"a+"

Opens for reading and appending; the appending operation includes the removal of the EOF marker before new data is written to the file and the EOF marker is restored after writing is complete; creates the file first if it doesn't exist.

When a file is opened with the "a" or "a+" access type, all write operations occur at the end of the file. The file pointer can be repositioned using fseek or rewind, but is always moved back to the end of the file before any write operation is carried out. Thus, existing data cannot be overwritten.

The "a" mode does not remove the EOF marker before appending to the file. After appending has occurred, the MS-DOS TYPE command only shows data up to the original EOF marker and not any data appended to the file. The "a+" mode does remove the EOF marker before appending to the file. After appending, the MS-DOS TYPE command shows all data in the file. The "a+" mode is required for appending to a stream file that is terminated with the CTRL+Z EOF marker.

When the "r+", "w+", or "a+" access type is specified, both reading and writing are allowed (the file is said to be open for "update"). However, when you switch between reading and writing, there must be an intervening fflush, fsetpos, fseek, or rewind operation. The current position can be specified for the fsetpos or fseek operation, if desired.

In addition to the above values, the following characters can be included in mode to specify the translation mode for newline characters:

t

Open in text (translated) mode. In this mode, CTRL+Z is interpreted as an end-of-file character on input. In files opened for reading/writing with "a+", fopen checks for a CTRL+Z at the end of the file and removes it, if possible. This is done because using fseek and ftell to move within a file that ends with a CTRL+Z, may cause fseek to behave improperly near the end of the file.

Also, in text mode, carriage return–linefeed combinations are translated into single linefeeds on input, and linefeed characters are translated to carriage return–linefeed combinations on output. When a Unicode stream-I/O function operates in text mode (the default), the source or destination stream is assumed to be a sequence of multibyte characters. Therefore, the Unicode stream-input functions convert multibyte characters to wide characters (as if by a call to the mbtowc function). For the same reason, the Unicode stream-output functions convert wide characters to multibyte characters (as if by a call to the wctomb function).

b

Open in binary (untranslated) mode; translations involving carriage-return and linefeed characters are suppressed.

If t or b is not given in mode, the default translation mode is defined by the global variable _fmode. If t or b is prefixed to the argument, the function fails and returns NULL.

For more information about using text and binary modes in Unicode and multibyte stream-I/O, see Text and Binary Mode File I/O and Unicode Stream I/O in Text and Binary Modes.

c

Enable the commit flag for the associated filename so that the contents of the file buffer are written directly to disk if either fflush or _flushall is called.

n

Reset the commit flag for the associated filename to "no-commit." This is the default. It also overrides the global commit flag if you link your program with COMMODE.OBJ. The global commit flag default is "no-commit" unless you explicitly link your program with COMMODE.OBJ.

Valid characters for the mode string used in fopen and _fdopen correspond to oflag arguments used in _open and _sopen, as follows.

Characters in mode String

Equivalent oflag Value for _open/_sopen

a

_O_WRONLY | _O_APPEND (usually _O_WRONLY | _O_CREAT | _O_APPEND)

a+

_O_RDWR | _O_APPEND (usually _O_RDWR | _O_APPEND | _O_CREAT )

r

_O_RDONLY

r+

_O_RDWR

w

_O_WRONLY (usually _O_WRONLY | _O_CREAT | _O_TRUNC)

w+

_O_RDWR (usually _O_RDWR | _O_CREAT | _O_TRUNC)

b

_O_BINARY

t

_O_TEXT

c

None 

n

None 

 

Example

/* FOPEN.C: This program opens files named "data"

* and "data2".It  uses fclose to close "data" and

* _fcloseall to close all remaining files.

*/

 

#include

 

FILE *stream, *stream2;

 

void main( void )

{

  int numclosed;

 

  /* Open for read (will fail if file "data" does not exist) */

  if( (stream  = fopen( "data", "r" )) == NULL )

     printf( "The file 'data' was not opened/n" );

  else

     printf( "The file 'data' was opened/n" );

 

  /* Open for write */

  if( (stream2 = fopen( "data2", "w+" )) == NULL )

     printf( "The file 'data2' was not opened/n" );

  else

     printf( "The file 'data2' was opened/n" );

 

  /* Close stream */

  if( fclose( stream ) )

     printf( "The file 'data' was not closed/n" );

 

  /* All other files are closed: */

  numclosed = _fcloseall( );

  printf( "Number of files closed by _fcloseall: %u/n", numclosed );

}

 

Output

The file 'data' was opened

The file 'data2' was opened

Number of files closed by _fcloseall: 1

===============================================

4.C++中對文件操作

void CFileView::OnFileWrite()  

    ofstream ofs("4.txt");//
構造一個對象傳遞文件名4.txt 
    //C++
中寫入文件可以用這個類 
    ofs.write("www.baidu.com",strlen("www.baidu.com")); 
    ofs.close();
 
 } 
 
void CFileView::OnFileRead()  

    ifstream ifs("4.txt");//
讀入一個文件用這個類 
    char ch[100]; 
    memset(ch,0,100);//
將字符數組中的內存都設爲零 
    ifs.read(ch,100); 
    ifs.close(); 
    MessageBox(ch);
 
}

因爲用到了ofstreamifstream,所以還要在這個文件中包含頭文件:

#include  //文件中用到了ofstream類,所以要包含這個頭文件

 

5.win32API中對文件操作的幾個函數

void CFileView::OnFileWrite()  

    HANDLE hFile; 
    hFile=CreateFile("5.txt",GENERIC_WRITE,0,NULL, 
        CREATE_NEW,FILE_ATTRIBUTE_NORMAL,NULL);//
創建文件 
    DWORD dwWrites;//
定義一個變量用來接收實際寫入的字節數 
    WriteFile(hFile,"http://www.baidu.com",strlen("http://www.baidu.com"), 
        &dwWrites,NULL); 
    CloseHandle(hFile);//
關閉文件,因爲文件對象是用句柄來標識的 
  } 
 
void CFileView::OnFileRead()  

    HANDLE hFile; 
    hFile=CreateFile("5.txt",GENERIC_READ,0,NULL,OPEN_EXISTING, 
        FILE_ATTRIBUTE_NORMAL,NULL); 
    char ch[100]; 
    DWORD dwReads;//
這個變量用來接收實際讀取的字節數 
    ReadFile(hFile,ch,100,&dwReads,NULL);//
讀取文件 
    ch[dwReads]=0;//
將實際數據的下一個數據設置爲
    CloseHandle(hFile); 
    MessageBox(ch);
 
 } 

注:在win32 API中的CreateFile不光只是可以對文件進行操作,它還可以對其它的數據對象進行操作。

 

6.MFC當中對文件操作的類

void CFileView::OnFileWrite()  

    CFile file("6.txt",CFile::modeCreate|CFile::modeWrite);//
定義一個CFile對象 
    file.Write("http://www.baidu.com",strlen("http://www.baidu.com"));//
寫入文件 

 
void CFileView::OnFileRead()  

    CFile file("6.txt",CFile::modeRead);//
以讀模式創建一個文件 
    char *pBuf; 
    DWORD dwFileLen; 
    dwFileLen=file.GetLength();//
獲取文件長度 
    pBuf=new char[dwFileLen+1]; 
    pBuf[dwFileLen]=0;//
pBuf中文件最後一字節的下一個字節置
    file.Read(pBuf,dwFileLen); 
    file.Close(); 
    MessageBox(pBuf);
 
 }

 

7.添加打開和另存爲文件對話框

void CFileView::OnFileWrite()  

    CFileDialog fileDlg(FALSE); 
    //Set to TRUE to construct a File Open dialog box or FALSE to construct a File Save As dialog box 
    fileDlg.m_ofn.lpstrTitle="
文件保存對話框"
    fileDlg.m_ofn.lpstrFilter="Text Files(*.txt)/0*.txt/0All Files(*.*)/0*.*/0/0"
    //
設置過濾器,/0表示字符串的結尾,過濾器的結尾要以/0/0結尾 
    fileDlg.m_ofn.lpstrDefExt="txt";//
設置默認的擴展名 
    if(fileDlg.DoModal()) 
    { 
        CFile file(fileDlg.GetFileName(),CFile::modeCreate|CFile::modeWrite); 
        file.Write("http://www.baidu.com",strlen("http://www.baidu.com"));//
寫入文件 
        file.Close(); 
    }
 

 
void CFileView::OnFileRead()  

    CFileDialog fileDlg(TRUE); 
    //Set to TRUE to construct a File Open dialog box or FALSE to construct a File Save As dialog box 
    fileDlg.m_ofn.lpstrTitle="
文件打開對話框"
    fileDlg.m_ofn.lpstrFilter="Text Files(*.txt)/0*.txt/0All Files(*.*)/0*.*/0/0"
    //
設置過濾器,/0表示字符串的結尾,過濾器的結尾要以/0/0結尾 
    if(fileDlg.DoModal()) 
    { 
        CFile file(fileDlg.GetFileName(),CFile::modeRead); 
        char *pBuf; 
        DWORD dwFileLen; 
        dwFileLen=file.GetLength();//
獲取文件長度 
        pBuf=new char[dwFileLen+1]; 
        pBuf[dwFileLen]=0;//
pBuf中文件最後一字節的下一個字節置
        file.Read(pBuf,dwFileLen); 
        file.Close(); 
        MessageBox(pBuf); 
    }
 
}

 

8.將初始化信息寫到ini文件中

CFileApp::InitInstance()添加:

    SetRegistryKey(_T("Local AppWizard-Generated Applications"));

    WriteProfileString("http://www.baidu.com","admin","luowei");//寫入win.ini當中

    LoadStdProfileSettings(); // Load standard INI file options (including MRU)

 

9.讀出ini文件中的信息

CFileApp::InitInstance()編輯:

SetRegistryKey(_T("Local AppWizard-Generated Applications"));

    //::WriteProfileString("http://www.baidu.com","admin","luowei");//寫入win.ini當中

    CString str;

    ::GetProfileString("http://www.baidu.com","admin","win_ini",str.GetBuffer(100),100);

    AfxMessageBox(str);

    LoadStdProfileSettings(); // Load standard INI file options (including MRU)

 

10.寫入和讀取註冊表信息

CFileApp::InitInstance()編輯,

寫入:

    //SetRegistryKey(_T("Local AppWizard-Generated Applications"));//設置註冊表的位置 
    SetRegistryKey(_T("http://www.luowei.org"));//
設置註冊表的位置 
     WriteProfileString("http://www.baidu.com","admin","luowei");//
寫入註冊表當中 
     LoadStdProfileSettings();  // Load standard INI file options (including MRU)

讀取:

        SetRegistryKey(_T("http://www.luowei.org"));//設置註冊表的位置 
    //WriteProfileString("http://www.baidu.com","admin","luowei");//
寫入註冊表當中 
    CString str; 
    str=GetProfileString("http://www.baidu.com","admin"); 
    AfxMessageBox(str);
 
    LoadStdProfileSettings();  // Load standard INI file options (including MRU)

11.註冊表編程

在文件菜單下添加兩菜單項,分別爲:id:IDM_REG_WRITE(寫註冊表)id:IDM_REG_READ (讀註冊表)

寫入和讀取字符串類型的值

void CFileView::OnRegWrite()  

    // TODO: Add your command handler code here 
    HKEY hKey; 
    RegCreateKey(HKEY_LOCAL_MACHINE,"software//http://www.luowei.org//admin",&hKey); 
    //
創建一個註冊表項 
    RegSetValue(hKey,NULL,REG_SZ,"luowei",strlen("luowei")); 
    //
設置註冊表的值,第二個參數NULL,指定了缺省名字賦值 
    RegCloseKey(hKey);//
關閉句柄 

 void CFileView::OnRegRead()  

    // TODO: Add your command handler code here 
    //
獲取字符串類型的數據 
    LONG lValue; 
    RegQueryValue(HKEY_LOCAL_MACHINE,"software//http://www.luowei.org//admin",NULL,&lValue); 
    //
第三個參數設置爲NULL,則返回註冊表中註冊表項的值的長度 
    char *pBuf=new char[lValue];//
分配內存,lValue包含了多餘的空字符,所以這不需要多分配一個字節 
    RegQueryValue(HKEY_LOCAL_MACHINE,"software//http://www.luowei.org//admin",pBuf,&lValue); 
    //
獲取註冊表中註冊表項的值 
    MessageBox(pBuf);
 
}

12.讀取指定類型的註冊表值

void CFileView::OnRegWrite()  

    HKEY hKey; 
    DWORD dwAge=30
    RegCreateKey(HKEY_LOCAL_MACHINE,"software//http://www.luowei.org//admin",&hKey); 
    //
創建一個註冊表項 
    RegSetValueEx(hKey,"age",0,REG_DWORD,(CONST BYTE*)&dwAge,4); 
    RegCloseKey(hKey);//
關閉句柄 

 void CFileView::OnRegRead()  

    HKEY hKey;//
用來存放打開的表項的返回值 
    RegOpenKey(HKEY_LOCAL_MACHINE,"software//http://www.luowei.org//admin",&hKey); 
    //
打開註冊表項 
    DWORD dwType; 
    DWORD dwValue; 
    DWORD dwAge; 
    RegQueryValueEx(hKey,"age",0,&dwType,(LPBYTE)&dwAge,&dwValue); 
    //
獲得註冊表項的值 
    CString str; 
    str.Format("age=%d",dwAge); 
    MessageBox(str);
 
 }

發佈了69 篇原創文章 · 獲贊 6 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章