从 Ubuntu 中的 cpp 程序创建新文件
Creating a new file from a cpp program in Ubuntu
如何从 Ubuntu 中的 cpp 程序创建新文件,它与 windows 有什么不同。
如果您使用 linux 和 gcc/g++ 命令行编译工具,
编译程序:
g++ your_program.cpp -o your_program
您可以使用以下命令为文件添加执行权限:
sudo chmod a+x your_program
然后双击,就会执行
或:
你可以使用像 Code::Blocks / CLion
这样的 IDE
声明一个流class 文件并以写入模式打开该文本文件。如果该文件不存在,则它会创建一个新的文本文件。然后检查文件是否不存在或未创建然后 return false 否则 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;
}
如何从 Ubuntu 中的 cpp 程序创建新文件,它与 windows 有什么不同。
如果您使用 linux 和 gcc/g++ 命令行编译工具, 编译程序:
g++ your_program.cpp -o your_program
您可以使用以下命令为文件添加执行权限:
sudo chmod a+x your_program
然后双击,就会执行
或: 你可以使用像 Code::Blocks / CLion
这样的 IDE声明一个流class 文件并以写入模式打开该文本文件。如果该文件不存在,则它会创建一个新的文本文件。然后检查文件是否不存在或未创建然后 return false 否则 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;
}