Reputation: 51
I'm writing a program that searches for files. This block of code writes a folder name to a stringstream, preceding it with a "./" so that it can be used to change the directory. It then changes the directory and informs the user of the change.
stringstream maindir;
maindir << "./" << crntmainfile;
maindir.str().copy(maindirectory, 260, 0);
_chdir(maindirectory);
std::cout << maindirectory;
std::cout << "Main directory changed: " << maindirectory << "\n";
My problem is that maindirectory
has a bunch of extra characters at the end. I'm assuming that this has to do with the fact that it's a 260 length array with maybe 20 characters in it and the extra characters are whatever happens to be occupying the unwritten memory. If this is my problem, how do I fix it?
EDIT:
I've determined that crntmainfile
is null terminated, but the terminator is lost when it's written to maindir
. What's causing this? Does <<
simply not write null characters to stringstreams? How do I fix it?
EDIT:
I solved my problem by doing maindir.put(0);
after maindir << "./" << crntmainfile;
to manually null terminate the string.
Upvotes: 1
Views: 1171
Reputation: 5684
std::string::copy
does not append a null character at the end of the copied content.
why don't you just do this
maindir << "./" << crntmainfile ;
maindir >> maindirectory;
maindir.clear();
Upvotes: 1
Reputation: 153919
std::string::copy
doesn't '\0' terminate the target, so you have to do this yourself. A possibly better solution would be:
std::string mainDirectory( maindir.str() );
_chdir( mainDirectory.c_str() );
, and not use a char[]
at all.
Upvotes: 2