我一直在网上搜索以解决上述问题,但到目前为止没有成功。我将在下面更详细地描述这个问题。
我的程序只包含一个 .cpp 文件。如果打开此文件,程序应显示“test.txt”中的文本。否则,它应该显示“无法打开...”消息。问题如下:
我打开终端,转到包含我的文件的目录,使用常用命令编译和运行:“g++ main.cpp”和“./a.out”。当我以这种方式运行程序时,直接使用终端,程序可以正常工作。文本文件存在时显示文本,不存在时输出错误。当我双击unix 可执行文件“a.out”时,即使文本文件存在并且与可执行文件并排放置,程序也会显示“无法打开...”消息。我不知道当时该怎么想。除了下面的内容之外,代码还应该包含其他内容吗?
操作系统: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]