Search code examples
c++loggingfile-ioofstream

How to create file using ofstream in software's code


I am working on a software I have a task to make changes in software to add certain feature for which I need to log data .I am trying to create a log file using ofstream but I dont know why it is not creating file at any location I tried .I am having code and I am attaching that to existing software process.

ofstream k;
k.open("ko.txt",ios::app);
if (!k)
    {
        OutputDebugString(_T("file not created"));
        return 1;
    }

The code above always prints file not created. I have tried location %TMP%/orgName/Logs/ko.txt I am not able to create the log file


Solution

  • If k.open("ko.txt",ios::app); does not works that means you do not have the right to create the file in the current directory or you cannot modify the file

    Under Windows you can create the file into the directory Documents of the current user, and you can get the user home dir using getenv("USERPROFILE") or get the user name through getenv("USERNAME"), the goal is to make the path C:\\Users\<usename>\\Documents\\ko.txt :

    std::string path = std::string(getenv("USERPROFILE")) + "\\Documents\\ko.txt";
    std::ofstream(path.c_str(), ios::app); // .c_str() useless since c++11
    
    if (!k)
    {
        OutputDebugString(_T("file not created"));
        return 1;
    }
    

    or

    std::string path = std::string(":\\Users\\") + getenv("USERNAME") + "\\Documents\\ko.txt";
    std::ofstream(path.c_str(), ios::app); // .c_str() useless since c++11
    
    if (!k)
    {
        OutputDebugString(_T("file not created"));
        return 1;
    }