2015-02-24 37 views
1

Visual Studio抱怨fopen。我找不到改變它的正確語法。我有:如何從fopen到fopen_s

FILE *filepoint = (fopen(fileName, "r")); 

FILE *filepoint = (fopen_s(&,fileName, "r")); 

什麼是第一個參數的休息嗎?

+4

'fopen_s' [記錄在MSDN](https://msdn.microsoft.com/en-us/library/z5hh6ee9.aspx)。第一個參數應該是'FILE **',而返回值是'errno_t'。 – Michael 2015-02-24 09:02:01

+1

谷歌「MSDN fopen_s」 – pmg 2015-02-24 09:02:15

+1

F1不再在Visual Studio中工作了嗎? – molbdnilo 2015-02-24 09:33:45

回答

15

fopen_s是與模式字符串並返回流指針和錯誤代碼不同的方法,一些額外的選項「安全」變種fopen。它是由微軟發明的,並進入C標準:它被記錄在最新的C11標準草案的附錄K.3.5.2.2中。當然,它完全記錄在Microsoft在線幫助中。你似乎並不瞭解C.指針傳遞到輸出變量在你的榜樣的概念,你應該通過的filepoint地址作爲第一個參數:

errno_t err = fopen_s(&filepoint, fileName, "r"); 

下面是一個完整的例子:

#include <errno.h> 
#include <stdio.h> 
#include <string.h> 
... 
FILE *filepoint; 
errno_t err; 

if ((err = fopen_s(&filepoint, fileName, "r")) != 0) { 
    // File could not be opened. filepoint was set to NULL 
    // error code is returned in err. 
    // error message can be retrieved with strerror(err); 
    fprintf(stderr, "cannot open file '%s': %s\n", 
      fileName, strerror(err)); 
    // If your environment insists on using so called secure 
    // functions, use this instead: 
    char buf[strerrorlen_s(err) + 1]; 
    strerror_s(buf, sizeof buf, err); 
    fprintf_s(stderr, "cannot open file '%s': %s\n", 
       fileName, buf); 
} else { 
    // File was opened, filepoint can be used to read the stream. 
} 

微軟對C99的支持很笨重和不完整。 Visual Studio會生成有效代碼警告,強制使用標準但可選的擴展,但在這種情況下似乎不支持strerrorlen_s。有關更多信息,請參閱Missing C11 strerrorlen_s function under MSVC 2017

+1

strerror與fopen有類似的問題。考慮修改顯示使用strerror_s從我的+1? – Assimilater 2016-04-15 20:34:37

+1

@Assimilater:使用'fopen'沒有真正的問題*。 Visual Studio可能會產生一個警告,提示用戶使用'fopen_s()'編寫較少的可移植代碼。在'fopen_s'中增加的關於默認權限和獨佔模式的語義最好在'fdopen'可用時解決。 'strerror_s'要求用戶提供一個緩衝區,其長度應該首先通過調用'strerrorlen_s(err)'來計算。頭痛不值得麻煩。 – chqrlie 2016-04-16 19:15:36

+0

@Assimilater:不過,我編輯了答案並提供了兩種方法的代碼。 – chqrlie 2016-04-16 19:21:38