Search code examples
c++linuxmkdir

mkdir in /tmp not working: "Permission Denied"


I am trying to write a program to handle logging for an app. This is supposed to write logs to /tpm/app-name/log.txt. In order to do this, I need to make the directory app-name before writing, in case it doesn't exist. However, my code will not make the directory even though it runs with the correct permissions to do so.

I have tried: * using chdir to move to /tmp, and making the app-name directory afterwards * running the program with root privs (this is less than desirable and makes the code error out because of line 65 not having access to the current environment the rest of the system is running in).

I would like this program to be able to work from anywhere in the system.

My current code, in C++:

#include <iostream>
#include <string>
#include <cstdlib>
#include <fstream>
#include <bits/stdc++.h>
#include <sys/stat.h>
#include <sys/types.h>

using namespace std;

int main(int argc, char* argv[])
{
        string name = argv[1];
        string DIR = "/tmp/" + name;
        string LOG_LOCATION = DIR + "/log.txt";
        int len = DIR.length();
        char LOG_DIR[len + 1];
        strcpy(LOG_DIR, DIR.c_str());
        string OUTPUT_LOG = "Some error log text";
        ofstream log;
        cout << OUTPUT_LOG << endl;
        if (mkdir(LOG_DIR, 1777) == -1)
        {
            cerr << "ERROR:  " << strerror(errno) << endl;
        }
        else
        {
            cout << "Directory created";
        }
        log.open (LOG_LOCATION);
        log << OUTPUT_LOG << endl;
        log.close();
}

When using this program, the code compiles fine and even runs fine. It just doesn't make the directory, like I expect it to. Because of this, it also does not make the log file.

Thanks!


Solution

  • So I feel really stupid here, but I figured out what the answer to my own issue was.

    Firstly, I was passing the wrong info on stdin (the program was using this info to create the correct folder and I had the input on one of the options formatted wrong so it couldn't make the folder).

    Secondly, as @Mark Plotnick pointed out in the fourth comment, and as several others mentioned later on, I needed to add a leading zero to my the permission set on the line with mkdir.

    Moral of the story: make sure you pass the correct info on stdin and get your permissions right. XD