Skip to content
Advertisement

Creating a new file from a cpp program in Ubuntu [closed]

How do I create a new file from a cpp program in Ubuntu, and is it any different from windows.

Advertisement

Answer

Declare a stream class file and open that text file in writing mode. If the file is not present then it creates a new text file. Then check if the file does not exist or not created then return false otherwise return 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;
}

Source geeksforgeeks : C++ program to create a file

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement