I new to program, currently I followed pwd tutorial and came out the code below. I need to assign a variable to hold the current directory, and join it with other file as below.
#include <unistd.h>
#define GetCurrentDir getcwd
main (
uint port,... )
{
char buff[FILENAME_MAX];
GgetCurrentDir(buff, FILE_MAX);
FILE * fpointer ;
fpointer =fopen(buff+"/config_db","w"); //here
fclose(fpointer);
}
Wiki Part
In C++17, you are looking for filesystem
:
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
std::cout << "Current path is " << fs::current_path() << '\n';
}
In linux API, you are looking for getcwd
:
#include <string.h>
#include <unistd.h>
#include <iostream>
int main() {
char buf[1 << 10];
if (nullptr == getcwd(buf, sizeof(buf))) {
printf("errno = %s\n", strerror(errno));
} else {
std::cout << buf << std::endl;
}
}
Your Part
What you did wrong is that you cannot concatenate char *
or char []
with +
.
You should try strcat
from <cstring>
or apply +
after casting it
to std::string
.
#include <unistd.h>
#include <cstring>
#include <iostream>
#define GetCurrentDir getcwd
int main() {
char config_db_path[1 << 10];
GetCurrentDir(config_db_path, sizeof(config_db_path)); // a typo here
strcat(config_db_path, "/config_db");
// concatenate char * with strcat rather than +
FILE* fpointer = fopen(config_db_path, "w");
fclose(fpointer);
}