sabrre
sabrre

Reputation: 11

Executable fails to open files when double clicked

I have a C file called fileTest.c, which simply contains this:

#include <stdio.h>
int main()
{
    FILE* file =  fopen("test.txt","r");
    if (file == NULL) {
        printf("file failed to open\n");
    }
    fclose(file);
    return 0;
}

In the same directory, I have the test.txt file, which is empty.
I compile like so: gcc -Wall -std=gnu99 fileTest.c -o fileTest
Everything works perfectly (nothing is printed) if I run the resultant executable in the command line with ./fileTest, but when I try to run the executable by double clicking the exec file, I get "file failed to open". I'm using macOS High Sierra 10.13.3. Why is this happening?

Upvotes: 0

Views: 69

Answers (2)

user3629249
user3629249

Reputation: 16540

the following proposed code:

  1. outputs the current working directory path
  2. handles any error on the call to fopen()
  3. outputs a message if the call to fopen() is successful
  4. handles any error on the call to getcwd()

and now the proposed code:

#include <stdio.h>
#include <unistd.h>

int main( void )
{
    char pathName[1024];

    if( !getcwd( pathName, sizeof( pathName ) )
    {
        perror( "getcwd failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, getcwd successful

    printf( "current working Directory: %s\n", pathName );

    FILE* file =  fopen("test.txt","r");
    if (file == NULL)
    {
        perror("file failed to open\n");
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    printf( "call to fopen successful\n" );
    fclose(file);
    return 0;
}

However, it does not effect your question about why double clicking the executable does not cause the executable to be executed.

Upvotes: 0

haccks
haccks

Reputation: 106092

You need to provide the full path of the file "test.txt".

I tested it on the macOS High Sierra 10.13.2 with g++ 5.5.0. This is the output

enter image description here

Upvotes: 1

Related Questions