在vs编程中,经常会有这样的警告:warning C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use_CRT_SECURE_NO_WARNINGS. See online help for details. 是因为 fopen_s比fopen多了溢出检测,更安全一些。
在定义FILE * fp 之后,fopen的用法是: fp = fopen(filename,"w")。而对于fopen_s来说,还得定义另外一个变量errno_t err,然后err = fopen_s(&fp,filename,"w")。返回值的话,对于fopen来说,打开文件成功的话返回文件指针(赋值给fp),打开失败则返回NULL值;对于fopen_s来说,打开文件成功返回0,失败返回非0。
以下是win32的编辑框的保存和打开文件实例:
打开OnOpen( )
void OnOpen( ) { //打开文件读取文件数据; FILE * pFile; errno_t Err = fopen_s( &pFile, "E:\\WinEdit.txt", "r"); if ( Err != 0) { MessageBox( NULL, "打开文件失败!", "WinEdit", MB_OK ); } //将文件指针移动到结尾; fseek( pFile, 0, SEEK_END ); //获取文件的长度; long nFileLen = ftell( pFile ); //将文件指针移动到开头; fseek( pFile, 0, SEEK_SET ); //将文件的数据放入BUFF中; CHAR * pszBuff = ( CHAR * )malloc( nFileLen + 1 ); //清空; memset( pszBuff, 0, nFileLen + 1 ); //读取数据流; fread( pszBuff, nFileLen, 1, pFile ); fclose( pFile ); //将字符显示在EDIT窗口; SendMessage( g_hEdit, WM_SETTEXT, 0, ( LPARAM )pszBuff ); //释放内存; free( pszBuff ); }
保存OnSave( )
void OnSave( ) { //获取文字长度; LRESULT nTextLen = SendMessage( g_hEdit, WM_GETTEXTLENGTH, 0, 0 ); //获取文字; CHAR * pszBuff = NULL; pszBuff = ( CHAR * )malloc( nTextLen + 1 );//加1是为了防止越界; //分配BUFF的内存; memset( pszBuff, 0, nTextLen + 1 ); SendMessage( g_hEdit, WM_GETTEXT, nTextLen + 1, ( LPARAM )pszBuff ); //MessageBox( NULL, pszBuff, "WinEdit", MB_OK ); //保存文件; FILE * pFile; errno_t Err = fopen_s( &pFile, "E:\\WinEdit.txt", "w+"); if ( Err != 0) { MessageBox( NULL, "打开文件失败!", "WinEdit", MB_OK ); } fwrite( pszBuff, nTextLen, 1, pFile ); fclose( pFile ); //释放内存; free( pszBuff ); }