gpt4 book ai didi

c++ - 无法使用来自 QString 的 const char * 进行 fopen

转载 作者:行者123 更新时间:2023-11-30 02:19:07 25 4
gpt4 key购买 nike

为了动态打开一个文件,我传递了一个 QString 完整路径。如果作为变量传递,代码将失败。如果直接输入(不是通过变量),一切正常。这是怎么回事?

QString outputfile_qstring("C:/temp/out.mp3");
qDebug()<<"Original output file " << outputfile_qstring;
const char* outputfile = outputfile_qstring.toLatin1().constData();
qDebug()<<"Trying to open output file " << outputfile;
fout = fopen(outputfile, "wb+");
bool fileIsOpen = (fout != 0);
if ( !fileIsOpen ){
errStr_ = "Error opening the output file " + outputfile_qstring;
Q_ASSERT(false && "Could not open output file");
return false;
}

QString 到 const char * 的转换总是失败。

Original output file  "C:/temp/out.mp3"
Trying to open output file ????????????????????????aSC,_??r

最佳答案

问题出在这里:

const char* outputfile = outputfile_qstring.toLatin1().constData();

toLAtin1函数返回 QByteArray 按值。由于您不保存该对象,一旦表达式完成,它就会被破坏,从而使 outputfile 成为指向不存在数据的无效指针。

简单的解决方案是在调用 fopen 时直接使用表达式 outputfile_qstring.toLatin1().constData()。或者根本不使用 fopen 和 C 文件函数,只使用 Qt 文件。

关于c++ - 无法使用来自 QString 的 const char * 进行 fopen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51232526/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com