File creation in C++ on Xcode

前端 未结 3 1674
半阙折子戏
半阙折子戏 2020-12-19 13:37

This is supposed to create a file in my project directory called \"tuna.txt\". When I run it, it compiles successfully, however no file is created. I am on a mac using xcode

相关标签:
3条回答
  • 2020-12-19 13:46

    First of all you must check whether file has been opened/created or not. Then you should search for the file. Most probably the file hasn't been created yet. Here is the code:

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main(void){
    
    ofstream file;
    file.open("tuna.txt");
    if(file.is_open())
    {
       file << "I love tuna and tuna loves me!\n";
        file.close();
    }
    else
       cout<< "No file has been created!\n";
    
      return 0;
    }
    

    As you haven't given an absolute path to open function.See the folder where your code file is. Most probably the file will be there.

    0 讨论(0)
  • 2020-12-19 14:03

    In the Products folder (in the Project Navigator of the Navigator tab on the left-hand side of the Xcode IDE) you will find the executable. Click on the executable.

    If not already shown, make sure the Utilities tab on the right hand-side of the Xcode IDE is shown and the Show the file inspector is selected.

    From the inspector, you will see Full Path showing the path to the executable, and at the end of it, there will be an arrow. Clicking on this arrow will open up the Finder window to that location, and this is where you should also see all the text files and other files that have been created from within the program.

    PS. The reason that you couldn't find the tuna.txt file when using the search is because it is in a hidden folder along with the executable.

    0 讨论(0)
  • 2020-12-19 14:07

    I assure you that barring errors (which you're not checking for) a file is created. Xcode has a tendency to use the final build-dir as the current working directory when running from the IDE. you can change this by editing the active Scheme.

    1. Click on the Project box to the right of the STOP button on the main toolbar
    2. Select Edit Scheme
    3. Select the "Run" sub scheme in the left pane list.
    4. Select the Options tab,
    5. Check the "Use Custom Working Directory" checkbox
    6. Set the working directory to some place you know (like your project root folder).

    Note: This is also where you will setup any command line arguments (those are on the Arguments tab, not the Options tab), should you desire to do so.

    0 讨论(0)
提交回复
热议问题