2017-02-19 197 views
2

我不明白爲什麼這不起作用。爲什麼fopen無法正常工作?

#include <stdio.h> 

int main(void) { 
    FILE *in, *out; 
    // char *FULLPATH = "C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt\\ "; 
    // char *mode = "r"; 
    // in = fopen(FULLPATH, mode); 
    // 
    // if (in == NULL) { 
    //  perror("Can't open in file for some reason\n"); 
    //  exit (1); 
    // } 

    out = fopen("C:\\Users\\Jay\\c\\workspace\\I-OFiles\\out.txt", "w"); 

    if (out == NULL) { 
     perror("Can't open output file for some reason \n"); 
     exit(1); 
    } 

    fprintf(out, "foo U"); 
    fclose(in); 
    fclose(out); 
    return 0; 
} 

,如果我從註釋行中刪除//錯誤編譯器使是

:無效的參數

我不明白爲什麼(我讀了所有其他線程相關,而且什麼也沒有)。 它實際上編寫了out.txt文件,所以它看起來不像路徑拼寫錯誤的問題。

+8

'in.txt \\' - >'in.txt' –

+3

你確實有一個叫做'in.txt'目錄? – melpomene

+0

感謝@SouravGhosh,我不知道還有什麼可以嘗試的 – newbie

回答

3

刪除in.txt後的反斜槓。

1

輸入文件名看起來假:

"C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt\\ " 

文件名只是一個單一的空間" "in.txt可能不是一個目錄。

更改代碼:向前在Windows以及Unix中斜槓工作

const char *FULLPATH = "C:/Users/Jay/c/workspace/I-OFiles/in.txt"; 

爲更好的便攜性:

const char *FULLPATH = "C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt"; 

或最好。

此外,很容易提供更多關於爲什麼fopen()無法打開文件的信息。

下面是修改後的版本:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int main(void) { 
    FILE *in, *out; 

    in = fopen("C:/Users/Jay/c/workspace/I-OFiles/in.txt", "r"); 
    if (in == NULL) { 
     perror("Cannot open input file"); 
     exit(1); 
    } 

    out = fopen("C:/Users/Jay/c/workspace/I-OFiles/out.txt", "w"); 
    if (out == NULL) { 
     fclose(in); 
     perror("Cannot open output file"); 
     exit(1); 
    } 

    fprintf(out, "foo U"); 
    fclose(in); 
    fclose(out); 
    return 0; 
} 
+0

調用perror()將在其顯示的輸出中包含來自'strerror(errno)'的結果,而不必讓程序包含' errno.h'頭文件或'string.h'頭文件 – user3629249

+0

函數:exit()在stdlib.h頭文件中找到。所以這不會乾淨地編譯 – user3629249

+0

當第二次調用fopen()失敗時,第一次調用fopen()時,文件名 – user3629249

相關問題