我想用 c++ 在 ubuntu 中创建一个空文件,我尝试了很多方法,但它一直失败并显示此错误
错误:没有与 'std::basic_ofstream::open(std::cxxll::...
我的代码:
ifstream f(saltFile.c_str());
if (f.good())
{
cout << saltFile + " file already existed" << endl;
}
else
{
ofstream file;
file.open (saltFile, ios::out);
cout << saltFile << " created!" << endl;
}
如果你有C++11或更高版本的编译器,你当然可以使用:
else
{
ofstream file;
file.open (saltFile, ios::out);
cout << saltFile << " created!" << endl;
}
如果您有 C++11 之前的编译器,则需要稍微调整对
open()
的调用。
file.open (saltFile.c_str(), ios::out);
要创建一个可以使用 ofstream 的文件
#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
outfile << "Data";
return 0;
}
请不要忘记进行适当的错误处理:
#include <iostream>
#include <fstream>
#include <filesystem>
#include <spdlog/fmt/fmt.h>
#include <cerrno>
int main() {
auto const fileName = "/test.txt";
std::ofstream outfile (fileName);
if (not outfile.good()) {
auto const errNo = errno;
auto const errMsg = fmt::format("Failed to create file {}: {} : {}", fileName, errNo, std::strerror(errNo));
throw std::runtime_error(errMsg);
}
return 0;
}