Search code examples
c++macossublimetext3sublimetextfstream

Sublime Text, my file is stored in my home folder when I write a file using fstream on Mac


I'm using Sublime Text 3 on mac to write c++. I wrote some code that gets my cin value for the name and the age and write them in the file file.txt.

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

int main()
{
    string name;
    int age;
    ofstream file("file.txt", ios::out);
    cout<<"enter name: "<<endl;
    cin>>name;
    cout<<"enter age: "<<endl;
    cin>>age;
    file<<name<<" "<<age<<endl;
    return 0;
}

The problem is that "file.txt" file is stored in my home folder, not my current working directory. how can I store it in my current working directory? check this


Solution

  • That's too weird problem, I'm not 100% fully sure about macOS, but this works on Linux and Windows.

    #include <iostream>
    #include <fstream>
    
    int main(void) {
        std::ofstream file("./file.txt", std::ios::out); // --- here add './' prefix
        std::string name;
        int age;
    
        std::cout << "Enter your name: ";
        std::getline(std::cin, name); // use std::getline() for whitespaces
    
        std::cout << "Your age: ";
        std::cin >> age;
    
        file << name << ' ' << age << '\n';
    
        return 0;
    }
    

    Just add ./ before the file name to explicitly define the output directory of the file must the same where the program is actually running.

    Another solution

    If the aforementioned solution fails, try g++ -o your_program your_program.cpp and run the program again. If it works successfully as you expect, it's cleared that something's wrong in your Sublime Text settings.