I've been searching online to solve the above issue with no success so far. I will describe the issue in more details below.
My program contains only one .cpp file. The program should display text from "test.txt" if this file is opened. Otherwise, it should display the "Failed to open ..." message. The issue follows:
I open terminal, go to the directory containing my file, compile and run with the usual commands: "g++ main.cpp" and "./a.out". When I run my program in this way, using terminal directly, the program works correctly. It displays text when the text file exists and outputs error when it doesn't exist. When I double click the unix executable "a.out", even though the text file exists and is put side by side with the executable, the program displays "Failed to open ..." message. I don't know what to think at that point. Should code contain anything else besides what is below?
Operating system: OS X 10.9.5
#include <iostream>
#include <fstream>
using namespace std;
const int MAX_CHAR_READ = 100;
int main(int argc, const char * argv[])
{
ifstream read_file;
cout << endl << endl;
//Allocate dynamic memory
char * file = new char[strlen("test.txt") + 1];
char * text_line = new char[MAX_CHAR_READ + 1];
strcpy(file, "test.txt");
//Attempt to open a file for reading
read_file.open(file);
if(read_file.is_open() == true)
{
cout << "File: " << file << " is open!" << endl;
read_file.get(text_line, MAX_CHAR_READ, ';');
cout << text_line << endl;
read_file.close();
}
else
cout << "Failed to open: " << file << endl;
cout << endl << endl;
//Deallocate dynamic memory
delete [] file;
delete [] text_line;
return 0;
}
Program execution example using terminal manually:
$ cd Desktop/Other/Test
$ g++ main.cpp
$ ./a.out
File: test.txt is open!
Hello World!
$
Program execution example double clicking the same executable:
$/Users/vladimirmeshcheryakov/Desktop/Other/Test/a.out ; exit;
Failed to open: test.txt
logout
[Process completed]