0

Im trying to read a file with given by user aboslute path. This is how im getting this path:

const char* WavRead::getFilePath(){
  std::string input;
  std::cout << "Input wave file name: ";
  std::cin >> input;
  std::cin.get();
  filePath = input.c_str();
  return filePath;
}

Then im passing it like this:

void WavRead::run(){
  const char* temp_filePath;
  temp_filePath = WavRead::getFilePath();
  WavRead::readFile(temp_filePath);
}

And finally im trying to open a file with given absolute path (ex. D:\daisy.wav)

int WavRead::readFile(const char* filePath){
  wav_hdr wavHeader;
  int headerSize = sizeof(wav_hdr);
  FILE* wavFile = fopen(filePath, "r");
  if (wavFile == nullptr){
    fprintf(stderr, "Unable to open wave file: %s\n", filePath);
    return 1;
  }

  size_t bytesRead = fread(&wavHeader, 1, headerSize, wavFile);
  fprintf(stderr, "Header size: %d\n", bytesRead);
  return 0;
}

But this doesn't work. File doesn't load and cosnole shows me this answer:

"Unable to open wave file: !"

user3038744
  • 86
  • 1
  • 8
  • 3
    `input` is an automatic variable with a scope, delimiting its lifetime to the function's scope. So, every pointer pointing to it or one of its members will go out of scope as well. – cadaniluk Dec 12 '15 at 15:04

1 Answers1

2

The pointer filePath = input.c_str(); is valid only for the time the variable input exists. When you return from the function, this becomes invalid.

Consider returning the string instead:

std::string WavRead::getFilePath(){
  std::string input;
  ...
  return input;
}

and work with strings in the remainder of your code, unless you absolutely need to call a function requiring a char* argument, in which case you could then provide it safely using c_str().

Christophe
  • 68,716
  • 7
  • 72
  • 138