【问题标题】:Using fopen() with absolute path pointer [duplicate]将 fopen() 与绝对路径指针一起使用 [重复]
【发布时间】:2016-03-18 09:56:32
【问题描述】:

我正在尝试读取用户绝对路径给定的文件。 这就是我获得这条路径的方式:

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

然后我像这样传递它:

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

最后我试图用给定的绝对路径打开一个文件(例如 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;
}

但这不起作用。文件未加载,cosnole 向我显示了这个答案:

“无法打开波形文件:!”

【问题讨论】:

  • input 是一个具有范围的自动变量,将其生命周期限定为函数的范围。因此,每个指向它或其成员之一的指针也将超出范围。

标签: c++ pointers fopen


【解决方案1】:

指针filePath = input.c_str(); 仅在变量输入存在时有效。当您从函数返回时,这将变得无效。

考虑改为返回字符串:

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

并在代码的其余部分使用字符串,除非您绝对需要调用需要 char* 参数的函数,在这种情况下,您可以使用 c_str() 安全地提供它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-16
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多