今天使用公司代碼的日志模塊記錄程序運行的相關信息,發現日志總是只有兩條記錄,即程序啟動和結束,別的都沒有。跟蹤了很久,終於發現是日志輸出模塊被我修改了一個地方:把fopen改成了fopen_s,畢竟報了warning。但是這也是問題的根源!
下面的說明來自於msdn:
Files opened by fopen_s and _wfopen_s are not sharable. If you require that a file be sharable, use _fsopen, _wfsopen with the appropriate sharing mode constant (for example, _SH_DENYNO for read/write sharing).
fopen_s打開的文件不是共享讀寫的!但是日志模塊需要反復在同一個文件中讀寫,而且每次都調用了fopen_s,第二次調用的時候當然會出錯了,錯誤代碼是13,也就是EACCES (Permission denied)
這里應該使用_fsopen:
#include <stdio.h> #include <stdlib.h> #include <share.h> int main( void ) { FILE *stream; // Open output file for writing. Using _fsopen allows us to // ensure that no one else writes to the file while we are // writing to it. // if( (stream = _fsopen( "outfile", "wt", _SH_DENYWR )) != NULL ) { fprintf( stream, "No one else in the network can write " "to this file until we are done.\n" ); fclose( stream ); } // Now others can write to the file while we read it. system( "type outfile" ); }(以上代碼來自於msdn,版權歸原作者所有)