a kind person
a kind person

Reputation: 389

C - Why fopen doesn't work?

I have this very simple code:

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

int main (void)
    {
    FILE * file_ptr = NULL;

    file_ptr = fopen ("file.txt", "r");

    if (file_ptr == NULL)
        {
        puts ("Error!");
        return EXIT_FAILURE;
        }
    else
        {
        puts ("O.k.!");
        }

    return EXIT_SUCCESS;
    }

Output:

Error!

Why fopen doesn't work? The file is not protected, not opened elsewhere and is stored in the same folder as the *.exe of this program. I also tried it with giving the complete path to the file and with an array, in which the filename is stored. Everytime it puts out "Error!".

What's going on??

I'm using Eclipse Neon.2 Release (4.6.2) with newest cygwin gcc compiler on Windows 10 64bit.

Thank you for your help!

Upvotes: 2

Views: 6863

Answers (2)

user3386109
user3386109

Reputation: 34829

The problem was solved by changing the fopen to

file_ptr = fopen("xxyyzzqq.txt", "w");

and then searching the hard drive to see where the file was created.

Turns out that the file was created in the project source directory, and not the debug directory (where the .exe file is), unlike the old installation which used the debug directory as the working directory.

Upvotes: 3

user4513271
user4513271

Reputation:

perror might help.

FILE *file_ptr = fopen("file.txt", "r");
if (!file_ptr) {
  perror("fopen");
} else {
  printf("It's working!");
}

Similar question: fopen() not working in C

Upvotes: 1

Related Questions