small-j
small-j

Reputation: 309

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"); or specify an absolute path, I get "Unable to locate source file" all the time. Please help!

Upvotes: 0

Views: 258

Answers (3)

Weather Vane
Weather Vane

Reputation: 34583

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. 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.

#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.

Upvotes: 0

paulsm4
paulsm4

Reputation: 121881

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":

FILE *inputFile=fopen("I:\\Test\\main.cpp","r");

Upvotes: 3

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215617

The mode strings for read and write mode are "r" and "w", not "R" and "W". Using an invalid mode is probably what's causing fopen to fail.

Upvotes: 4

Related Questions