-2

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);
}
Alois
  • 130
  • 1
  • 2
  • 14

1 Answers1

4

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';
}

See cppreference filesystem

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;
  }
}

See linux man page getcwd

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);
}
tigertang
  • 445
  • 1
  • 6
  • 18
  • what about linux? filesystem is for windows right? – Alois Feb 07 '20 at 03:24
  • 1
    @Alois `std::filesystem` is for compilers that support `c++17`, no matter what platforms. – tigertang Feb 07 '20 at 03:28
  • Thanks @tigertang3. The previous error solved, but I have these errors now: PortSelection_main.c:22:5: warning: first argument of ‘int main(uint, ...)’ should be ‘int’ [-Wmain] int main ( ^~~~ PortSelection_main.c:22:5: warning: ‘int main(uint, ...)’ takes only zero or two arguments [-Wmain] PortSelection_main.c:22:5: warning: ‘int main(uint, ...)’ declared as variadic function [-Wmain] – Alois Feb 07 '20 at 07:08
  • you need to take a look at the template of c main function. uint should not be the 1st argument – tigertang Feb 07 '20 at 07:46