如何读写输入文件和输出文件

时间:2012-01-23 22:10:51

标签: c++ xcode macos

我正在尝试运行以下程序:

#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    ifstream inFile;
    ofstream outFile;
    double first=1.49, second=2.59, third=3.69, fourth=4.79;
    inFile.open("prices.txt");
    char response;
    if(!inFile.fail())
    {
        cout << "A file by the name prices.txt exists.\n" << "Do you want to continue and overwrite it\n" << " with the new data (y or n);"; cin >> response;
        if(tolower(response) == 'n')
        {
            cout << "The existing file will not be overwritten." << endl;
            return -1;

        }
    }
    outFile.open("prices.txt");
    if (inFile.fail())
    {
        cout << "\n The file does not exist and can not be opened" << endl;
        cout << "The file has been successfully opened for output." << endl;
        outFile << first << "\n" << second << "\n" << fourth << "\n" << endl;
        outFile.close();
        exit(1);
        cout << "The file has been successfully opened for output. " << endl;
        outFile << first << "\n" << second << "\n" << third << "\n" << fourth << endl;
        outFile.close();
        return 0;
    }
}

然而,该程序不会将值写入prices.txt文件。如果您在程序中说文件不存在则运行该程序。再次运行它说文件已经存在,如果你想覆盖它。事情是搜索我的Mac我无法在任何地方找到这个文件。

在Xcode中运行它时,我有什么想法?朋友在Visual Studio 2008中运行完全相同的代码并且它可以工作。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

您需要设置可执行文件的工作目录,因为您假设您的数据文件位于当前工作目录中。在Xcode 3.x中,您可以在Get Info的第一个选项卡中为可执行文件设置此项。在Xcode 4.x中它已被移动,但原理是相同的。

或者,您可以更改数据文件路径(例如,使它们成为绝对路径),这样您就不会对当前工作目录做出假设。

答案 1 :(得分:0)

您可能没有权限写入您尝试保存文件的目录。

此外,您的程序中存在错误,我确信是否存在调试原因。

    outFile.close();
    exit(1);

但是在你尝试写入文件之后不久就在那里,然后再次关闭它。