2015-02-09 69 views
0

我使用vs2013。VS2013文件打開錯誤C

#include <stdio.h> 

void main(){ 

    FILE *f; 
    char fname[] = "17_1.txt"; 

    if ((f = fopen_s(f,fname, "r+")) == NULL) 
    { 
     fprintf(stdout, "can't open the file\n"); 
     exit(1); 
    } 
    while (!feof(f)) 
    { 
     fscanf_s(f, "%d %s %d %d\n"); 
     fprintf(stdout, "%d %s %d %d \n"); 
    } 

    fclose(f); 
} 

但錯誤4錯誤C4700:未初始化的局部變量 'F' 使用 我看到了-_- 我要怎麼改?

+0

將'f'作爲參數傳遞給它所分配的同一行,也就是說,在未初始化時使用它。 – 2015-02-09 04:01:47

+0

這一行:'while(!feof(f))'feof函數從未設置,直到嘗試讀取文件結尾之後。因此,它不應該被用作循環控制元素。 – user3629249 2015-02-09 04:11:09

+0

這一行:'fscanf_s(f,「%d%s%d%d \ n」);'可能(或可能不會)成功。代碼應該始終檢查scanf系列函數的返回值,以確保操作成功。在這種情況下,因爲有4個轉換因子,返回的值應該是4.任何其他返回的值表示錯誤,或者如果要在編譯此文件時啓用所有警告,則EOF – user3629249 2015-02-09 04:13:16

回答

2

你似乎很困惑fopen_sfopen。的fopen_s簽名是:

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

fopen的簽名是:

FILE *fopen(const char *restrict filename, const char *restrict mode); 

你分別用這兩個函數的方法是:

FILE* f = NULL; 
errno_t e; 

if ((e = fopen_s(&f, fname, "r+")) != 0) 
{ 
    fprintf(stdout, "can't open the file\n"); 
} 

和:

if ((f = fopen(fname, "r+")) == NULL) 

如果發生錯誤,fopen設置爲errno

+0

要使用errno_t,代碼需要包含頭文件。 – user3629249 2015-02-09 04:15:44