将 fopen() 与绝对路径指针一起使用
Using fopen() with absolute path pointer
我正在尝试读取用户指定路径的文件。
这就是我获得这条路径的方式:
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 向我显示了这个答案:
"Unable to open wave file: !"
指针filePath = input.c_str();
仅在变量input存在时有效。当您从函数中 return 时,这将变得无效。
考虑 return 字符串:
std::string WavRead::getFilePath(){
std::string input;
...
return input;
}
并在代码的其余部分使用字符串,除非您绝对需要调用需要 char* 参数的函数,在这种情况下,您可以使用 c_str()
安全地提供它。
我正在尝试读取用户指定路径的文件。 这就是我获得这条路径的方式:
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 向我显示了这个答案:
"Unable to open wave file: !"
指针filePath = input.c_str();
仅在变量input存在时有效。当您从函数中 return 时,这将变得无效。
考虑 return 字符串:
std::string WavRead::getFilePath(){
std::string input;
...
return input;
}
并在代码的其余部分使用字符串,除非您绝对需要调用需要 char* 参数的函数,在这种情况下,您可以使用 c_str()
安全地提供它。