簡體   English   中英

如何使用C++在linux中創建一個空文件

[英]How to create an empty file in linux using c++

我想用 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;
}

如果你想要一個完全空的文件,你可以使用<fstream>std::ofstream ,甚至不調用對象。

注意:這假設該文件尚不存在。 如果是這樣,如果您想將其替換為空白文件,則應先將其刪除。

空文件創建

std::ofstream output(file_path);

創建包含內容的文件

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

有趣的旁注

在嘗試使用ofstream的構造函數之前,我嘗試了output << nullptr; 看看會發生什么……

在此處輸入圖片說明

珍貴

如果您有 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM