C++程序如何创建文件?代码实例

2021年3月20日14:14:49 发表评论 843 次浏览

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

方法:声明流类文件, 然后以写入模式打开该文本文件。如果该文件不存在, 那么它将创建一个新的文本文件。现在检查文件是否不存在或未创建, 然后返回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

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: