Home > Enterprise >  How do I have to describe an absolute path to a file in C ?
How do I have to describe an absolute path to a file in C ?

Time:10-27

I want to do a program in C that, when is executed (from anywhere), modifies a text file in a very specific path (and always the same one). To do so, I've defined the following function in C :

void ChangeCourse(string course)
{
    ofstream active_course;
    active_course.open("~/.universidad/curso_activo.txt");

    if (!curso_activo)
        cout << "Error: cant't open the file" << endl;
    else
    {
        active_course << course;
        curso_activo.close();
    }
}

When executing the program that calls the function, I get the message Error: cant't open the file and, indeed, no file is created.

How do I have to define the path of the file such a way the program could read it and find it, regardless of where the program was called.

Note that I'm running the program in macOS.

Hope I've explained my self and thank you in advance.

CodePudding user response:

~ is expanded (to your home directory) by the shell (that is to say, by the command line interpreter). It is not part of the *nix API per-se. (macOS is based on BSD Unix.)

Instead, you can expand the HOME environment variable with getenv() and append the rest of your path (including the filename) to that before opening it.

CodePudding user response:

You cant use ~/. to refer to the home directory of the user like you can do in the command shell.

You need to specify the full path, for example /home/zjanny/test.txt

CodePudding user response:

In C 17 you can use the filesystem library and hard code the path, if this is what you really want to do.

#include <filesystem>
#include <fstream>

namespace fs=std::filesystem;

int main() {

  fs::path p = "your-absolute-path-goes-here"; // 
  if(fs::exists(p)) {
    std::ofstream file(p);
    file << "Hello world!" << "\n";
  }
  return 0;  
}

CodePudding user response:

Unless the file/folder you are looking for is in the current directory that the program is run from, you have to pass in the absolute file path.

In macOS you should be able to select the file you want to open and hit cmd i to find the absolute path to a file.

  • Related