2017-02-19 196 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

相关问题