今天使用公司代碼的日誌模塊記錄程序運行的相關信息,發現日誌老是隻有兩條記錄,即程序啓動和結束,別的都沒有。跟蹤了好久,終於發現是日誌輸出模塊被我修改了一個地方:把fopen改爲了fopen_s,畢竟報了warning。可是這也是問題的根源!app
下面的說明來自於msdn:ui
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).this
fopen_s打開的文件不是共享讀寫的!可是日誌模塊須要反覆在同一個文件中讀寫,並且每次都調用了fopen_s,第二次調用的時候固然會出錯了,錯誤代碼是13,也就是EACCES (Permission denied)spa
這裏應該使用_fsopen:日誌
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
#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,版權歸原做者全部)code