2015-04-23 80 views
2

我想創建文件並在其上寫入一些數據,但是當我運行以下代碼時,程序運行出錯:錯誤1錯誤C2664:'errno_t fopen_s(FILE **,const char * const char *)':無法將參數1從'FILE *'轉換爲'FILE **'閱讀文件錯誤C_language

#include "stdafx.h" 
#include <stdio.h> 
#include <stdlib.h> 

FILE *myFile; 


int main() 
{ 
    int age; 
    age = 24; 
    fopen_s(myFile,"C:\\inetpub\\wwwroot\\DATA.EMP", "w"); 
    if (myFile == 0){ 
     printf("Error opening the file\n"); 
     exit(1); 
    } 
    fprintf(myFile, "I am %d years old \n", age); 
    fclose(myFile); 

    getchar(); 
    return 0; 
} 

可能是什麼原因?

+0

編譯器錯誤告訴你很清楚。 'fopen_s'需要'FILE **'類型的arg 1,並且你給它'FILE *'。嘗試使用第一個參數'&myFile'。 – kaylum

+0

我弄明白了,我已經宣佈爲FILE ** myFile;但它給了我另一個錯誤Degub斷言失敗! 程序:.... al studio 2013 \ projects \ file_pointer1 \ debug \ file_pointer1.exe文件:f:\ dd \ vctools \ crt \ stdio \ fopen.c行:159 表達式:(pfile!= NULL) #包括 #include FILE ** myFile; int main() { \t int age; \t年齡= 24; (myFile,「C:\\ inetpub \\ wwwroot \\ DATA.EMP」,「w」); \t if(myFile == 0){ \t \t printf(「打開文件時出錯\ n」); \t \t exit(1); \t} \t fprintf(* myFile,「我是%d歲以上\ n」,年齡); \t fclose(* myFile); \t getchar(); \t return 0; } – JFC

+0

不要那樣做!這將編譯,但會在運行時失敗,因爲你已經發現了。 fopen_s調用將決定第一個參數。你必須給它一個指向分配內存的指針。通過使你的變量'FILE **'你傳遞一個無效的指針給fopen_s。按照建議進行:聲明爲FILE *,並將'&myFile'傳遞給'fopen_s'。在進一步研究之前,你可能想刷一下指針。 – kaylum

回答

1

https://msdn.microsoft.com/en-us/library/z5hh6ee9.aspx

errno_t fopen_s( 
    FILE** pFile, 
    const char *filename, 
    const char *mode 
); 

因此,你的代碼應該是:

fopen_s(&myFile,"C:\\inetpub\\wwwroot\\DATA.EMP", "w"); 

注: & myFile。

並檢查您的返回值。

+0

謝謝,我錯過了,我應該參考數據將存儲在變量的地址 – JFC