如何使用c++在linux中创建空文件

问题描述 投票:0回答:4

我想用 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++ fstream
4个回答
14
投票

如果你想要一个完全空的文件,你可以使用

<fstream>
std::ofstream
,甚至不调用该对象。

注意:这假设该文件尚不存在。如果是这样,如果您希望将其替换为空白文件,则应先将其删除。

创建空文件

std::ofstream output(file_path);

创建包含内容的文件

std::ofstream output(file_path);
output << L"Hello, world!";

有趣的旁注

在尝试仅使用

ofstream
的构造函数之前,我尝试了
output << nullptr;
看看会发生什么......

珍贵


3
投票

如果你有C++11或更高版本的编译器,你当然可以使用:

else
{
    ofstream file;
    file.open (saltFile, ios::out);
    cout << saltFile << " created!" << endl;
}

如果您有 C++11 之前的编译器,则需要稍微调整对

open()
的调用。

file.open (saltFile.c_str(), ios::out);

1
投票

要创建一个可以使用 ofstream 的文件

#include <fstream>

int main() {  
std::ofstream outfile;

outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
 outfile << "Data"; 
return 0;
}

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.