上記の問題を解決するためにオンラインで検索してきましたが、これまでのところ成功していません。この問題については、以下で詳しく説明します。
プログラムに含まれる .cpp ファイルは 1 つだけです。このファイルが開かれている場合、プログラムは「test.txt」からのテキストを表示する必要があります。それ以外の場合は、"Failed to open ..." メッセージが表示されます。問題は次のとおりです。
ターミナルを開き、ファイルを含むディレクトリに移動し、通常のコマンド「g++ main.cpp」と「./a.out」でコンパイルして実行します。ターミナルを直接使用して、この方法でプログラムを実行すると、プログラムは正しく動作します。テキストファイルが存在する場合はテキストを表示し、存在しない場合はエラーを出力します。Unix 実行可能ファイル「a.out」をダブルクリックすると、テキスト ファイルが存在し、実行可能ファイルと並べて配置されているにもかかわらず、「Failed to open ...」というメッセージが表示されます。その時点で何を考えたらいいのかわからない。コードには、以下のもの以外に何かを含める必要がありますか?
オペレーティング システム: 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;
}
端末を手動で使用したプログラムの実行例:
$ cd Desktop/Other/Test
$ g++ main.cpp
$ ./a.out
File: test.txt is open!
Hello World!
$
同じ実行可能ファイルをダブルクリックして実行するプログラムの例:
$/Users/vladimirmeshcheryakov/Desktop/Other/Test/a.out ; exit;
Failed to open: test.txt
logout
[Process completed]