[英]C program fopen() does not open a file
I understand, there are thousands of problems like this, but I haven't managed to find the solution to my issue. 我了解,有成千上万的此类问题,但我还没有找到解决问题的方法。 Here is the code:
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main()
{
FILE *inputFile=fopen("I:\\Test\main.cpp","R");
FILE *outFile=fopen("I:\\Test\main2.cpp", "W");
if (inputFile==NULL) {
printf("Unable to locate source file");
_getch();
return 1;
}
int c;
int inSingleLine=0;
int inMultiLine=0;
int d=fgetc(inputFile);
while(c=fgetc(inputFile)!=EOF){
if (d==EOF) break;
if((c=='/') && (d=='*')) inMultiLine=1;
if ((c='*') && (d=='/')) inMultiLine=0;
if((c=='/')&& (d=='/')) inSingleLine=1;
if (c='\n') inSingleLine=0;
if (!inSingleLine && !inMultiLine) {
putc(c,outFile);
}
d=getc(inputFile);
}
// This is a test string
fclose(inputFile);
fclose(outFile);
/* And this is not a test
Actually not
*/
return 0;
}
No matter what I do, whether I put main.cpp to the same folder with the exe file and make it FILE *inputFile=fopen("main.cpp","R");
无论我做什么,是否都将main.cpp和exe文件放到同一文件夹中,并使其设置为
FILE *inputFile=fopen("main.cpp","R");
or specify an absolute path, I get "Unable to locate source file" all the time. 或指定绝对路径,我一直都显示“无法找到源文件”。 Please help!
请帮忙!
The mode strings for read and write mode are "r"
and "w"
, not "R"
and "W"
. 读写模式的模式字符串是
"r"
和"w"
,而不是"R"
和"W"
。 Using an invalid mode is probably what's causing fopen
to fail. 使用无效模式可能是导致
fopen
失败的原因。
int main()
{
FILE *inputFile=fopen("I:\\Test\main.cpp","R"); <-- This results in the string "I:\Testain.cpp"
...
Make sure you use two "\\" symbols (escape both back-slashes), and use lower-case "w" and "r": 确保使用两个“ \\”符号(两个反斜杠转义),并使用小写的“ w”和“ r”:
FILE *inputFile=fopen("I:\\Test\\main.cpp","r");
As above, you must "escape" a backslash with a double one. 如上所述,您必须“转义”带有两个反斜杠。 You should always check the return value from
fopen()
and then you can obtain a message based on errno
. 您应该始终检查
fopen()
的返回值,然后才能获得基于errno
的消息。 When I tried the following with a lower-case "r"
I got a compiler warning about the invalid escape sequence \\m
but the program was well behaved. 当我尝试使用小写的
"r"
执行以下操作时,收到了有关无效转义序列\\m
的编译器警告,但程序运行正常。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE *inputFile=fopen("I:\\Test\main.cpp","r");
printf("After trying to open\n");
if (inputFile == NULL)
printf ("%s\n", strerror(errno));
else
fclose(inputFile);
return 0;
}
I got: 我有:
After trying to open
No such file or directory
But when I tried it with an upper-case "R"
the program hung (MSVC), I don't know why. 但是,当我使用大写的
"R"
进行尝试时,程序挂起(MSVC),我不知道为什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.