从Ubuntu中的CPP程序创建新文件

Creating a new file from a cpp program in Ubuntu

本文关键字:文件 新文件 创建 Ubuntu 中的 CPP 程序      更新时间:2023-10-16

如何从ubuntu中的CPP程序创建一个新文件,与Windows有什么不同。

声明流类文件,并以书面模式打开该文本文件。如果文件不存在,则将创建一个新的文本文件。然后检查文件是否不存在,然后返回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