C++程序创建文件

问题陈述: 编写一个C++程序,使用文件处理创建文件,并检查文件是否成功创建。如果文件创建成功,则应打印“文件创建成功”,否则应打印一些错误消息。

null

方法: 声明一个流类文件,并以写入模式打开该文本文件。如果文件不存在,则会创建一个新的文本文件。现在检查文件是否不存在或未创建,然后返回false,否则返回true。

下面是创建文件的程序:

// C++ implementation to create a file
#include <bits/stdc++.h>
using namespace std;
// Driver code
int main()
{
// fstream is Stream class to both
// read and write from/to files.
// file is object of fstream class
fstream file;
// opening file "Gfg.txt"
// in out(write) mode
// ios::out Open for output operations.
file.open( "Gfg.txt" ,ios::out);
// If no file is created, then
// show the error message.
if (!file)
{
cout<< "Error in creating file!!!" ;
return 0;
}
cout<< "File created successfully." ;
// 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;
}


输出: img

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享