我无法弄清楚为什么这不起作用。
#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文件,所以它看起来不像是路径拼写错误的问题。
答案 0 :(得分:3)
在in.txt
之后删除反斜杠。
答案 1 :(得分:1)
输入文件名似乎是伪造的:
"C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt\\ "
文件名只是一个空格" "
,in.txt
可能不是目录。
将代码更改为:
const char *FULLPATH = "C:\\Users\\Jay\\c\\workspace\\I-OFiles\\in.txt";
或者最好:
const char *FULLPATH = "C:/Users/Jay/c/workspace/I-OFiles/in.txt";
为了更好的可移植性,因为正斜杠可以在Windows和Unix中使用。
此外,很容易提供有关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;
}
答案 2 :(得分:0)
将反斜杠更改为斜杠。 也许你没有权限或类似的东西。
out = fopen("C://Users//Jay//c//workspace//I-OFiles//out.txt", "w");
if (!out)
perror("fopen");
return 0;