Jump to content
  • Advertisement
Sign in to follow this  
Genjix

getcwd/chdir c++ equivalents (boost?).

This topic is 4965 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

for some reason, my call to dirname (2nd line in main), seg faults. why?
#include <iostream>
#include <string>
#include <libgen.h>
#include <unistd.h>
using namespace std;

string &WorkingDirectory()
{
	static char cpath[128];
	static string retpath;

	retpath = getcwd(cpath,128);

	return retpath;
}

void ChangeDirectory(const char *path)
{
	chdir(path);
}

int main()
{
	cout << "Path : " << WorkingDirectory() << "\n";
	cout << "Dirname : " << dirname("../hhhj.xml") << "\n";
	ChangeDirectory("..");
	cout << "Path : " << WorkingDirectory() << "\n";

	return 0;
}


What c++ equivalents should I be using? (boost::filesystem??? sorry, i couldn't find it in docs, eventhough i know it exists).

Share this post


Link to post
Share on other sites
Advertisement
The dirname function is allowed to modify its argument. And since you're sending a constant string it's probably trying to write into a read-only segment.

Share this post


Link to post
Share on other sites
Quote:
Original post by Genjix
aha, makes sense... i would've thought the compiler would've warned though :/
Both C and C++ implicitly convert string literals to non-const char pointers when used in an expression, it's a backwards compability thing.

Share this post


Link to post
Share on other sites
After checking out the boost::filesystem example found here and some general probing, I believe the equivilants would be:

getcwd =
boost::filesystem::path full_path( boost::filesystem::current_path() );

dirname =
//if it's a directory return it:
if ( boost::filesystem::is_directory( path ) ) return path;
//otherwise return the parent path, and assume it's a directory:
return path.branch_path();

chdir =
//No direct equivilant. Instead, use path and it's members.

Example:

C version:

chdir("..");
FILE * f = fopen( "pie.txt" , "r" );

boost version:

using namespace boost::filesystem;
using namespace std;

path my_cwd ( current_directory() );
my_cwd /= "..";
ifstream f( my_cwd / "pie.txt" );

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!