声明流类文件并以写入模式打开该文本文件。如果文件不存在,则会创建新的文本文件。然后检查文件是否不存在或者没有创建,然后返回false,否则返回true。
#include <iostream> #include <fstream> #include <string> using namespace std; // Driver code int main() { const char *path = "/home/user/Gfg.txt"; // fstream is Stream class to both // read and write from/to files. // file is object of fstream class fstream file(path); // opening file "Gfg.txt" // in out(write) mode // ios::out Open for output operations. file.open(path, ios::out); // If no file is created, then // show the error message. if (!file) { cout << "Error in creating file!!!" << endl; return 0; } cout << "File created successfully." << endl; // closing the file. // The reason you need to call close() // at the end of the loop is that trying // to open a new file without closing the // first file will fail. file.close(); return 0; }
资源 geeksforgeeks:用于创建文件的C ++程序
如果你使用linux与gcc / g ++命令行编译工具, 编译程序:
g++ your_program.cpp -o your_program
您可以使用以下命令为文件添加执行权限:
sudo chmod a+x your_program
然后双击它,它将执行
要么: 你可以使用像Code :: Blocks / CLion这样的IDE