在C++中创建文件

lg40wkob  于 11个月前  发布在  其他
关注(0)|答案(7)|浏览(121)

我想用C++创建一个文件,但是我不知道怎么做。例如,我想创建一个名为Hello.txt的文本文件。
有人能帮我吗?

xiozqbni

xiozqbni1#

一种方法是创建一个ofstream类的示例,并使用它来写入你的文件。这里有一个链接到一个网站,其中有一些示例代码,以及关于大多数C++实现中可用的标准工具的更多信息:
ofstream reference
为了完整起见,这里有一些示例代码:

// using ofstream constructors.
#include <iostream>
#include <fstream>  

std::ofstream outfile ("test.txt");

outfile << "my text here!" << std::endl;

outfile.close();

字符串
你想使用std::endl结束你的行。另一种方法是使用'\n'字符。这两件事是不同的,std::endl刷新缓冲区并立即写入输出,而'\n'允许outfile将所有输出放入缓冲区,然后再写入。

rjjhvcjd

rjjhvcjd2#

用一个文件流来做这件事。当一个std::ofstream被关闭时,文件被创建。我更喜欢下面的代码,因为OP只要求创建一个文件,而不是在里面写:

#include <fstream>

int main()
{
    std::ofstream { "Hello.txt" };
    // Hello.txt has been created here
}

字符串
流在创建后立即被销毁,因此流在析构函数中被关闭,从而创建了文件。

yqyhoc1h

yqyhoc1h3#

#include <iostream>
#include <fstream>

int main() {
  std::ofstream o("Hello.txt");

  o << "Hello, World\n" << std::endl;

  return 0;
}

字符串

lnlaulya

lnlaulya4#

以下是我的解决方案:

#include <fstream>

int main()
{
    std::ofstream ("Hello.txt");
    return 0;
}

字符串
文件(Hello.txt)即使在没有ofstream名称的情况下也会创建,这就是与Boiethios先生的答案不同的地方。

hfyxw5xn

hfyxw5xn5#

#include <iostream>
#include <fstream>
#include <string>

std::string filename = "/tmp/filename.txt";

int main() {
  std::ofstream o(filename);

  o << "Hello, World\n";

  return 0;
}

字符串
这就是我必须做的,以便使用变量作为文件名,而不是常规字符串。

6yt4nkrj

6yt4nkrj6#

如果你想创建一个包含一些内容的文件,并且不需要处理ofstream,你可以简单地写:

#include <fstream>

int main() {
    std::ofstream("file.txt") << "file content";
}

字符串
无需手动关闭文件,处理变量等。文件在同一行中创建,写入和关闭。

2vuwiymt

2vuwiymt7#

/*I am working with turbo c++ compiler so namespace std is not used by me.Also i am familiar with turbo.*/

#include<iostream.h>
#include<iomanip.h>
#include<conio.h>
#include<fstream.h> //required while dealing with files
void main ()
{
clrscr();
ofstream fout; //object created **fout**
fout.open("your desired file name + extension");
fout<<"contents to be written inside the file"<<endl;
fout.close();
getch();
}

字符串
运行程序后,该文件将在编译器文件夹本身的bin文件夹中创建。

相关问题