【发布时间】:2009-01-25 19:15:12
【问题描述】:
我想使用 C++ 创建一个文件,但我不知道该怎么做。例如,我想创建一个名为Hello.txt 的文本文件。
谁能帮帮我?
【问题讨论】:
我想使用 C++ 创建一个文件,但我不知道该怎么做。例如,我想创建一个名为Hello.txt 的文本文件。
谁能帮帮我?
【问题讨论】:
一种方法是创建 ofstream 类的一个实例,并使用它来写入您的文件。这是一个网站链接,其中包含一些示例代码,以及有关大多数 C++ 实现中可用的标准工具的更多信息:
为了完整起见,这里有一些示例代码:
// 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 将所有输出放入缓冲区并可能稍后再写入。
【讨论】:
使用文件流执行此操作。当std::ofstream 被关闭时,文件被创建。我更喜欢下面的代码,因为 OP 只要求创建一个文件,而不是在其中写入:
#include <fstream>
int main()
{
std::ofstream { "Hello.txt" };
// Hello.txt has been created here
}
流在创建后立即被销毁,因此流在析构函数中关闭,因此文件被创建。
【讨论】:
() 与{},只是由于析构函数正在运行。但你是对的,有一个错误。我已经恢复到以前的版本,有一个错误的版本。
#include <iostream>
#include <fstream>
int main() {
std::ofstream o("Hello.txt");
o << "Hello, World\n" << std::endl;
return 0;
}
【讨论】:
这是我的解决方案:
#include <fstream>
int main()
{
std::ofstream ("Hello.txt");
return 0;
}
即使没有ofstream名称也会创建文件(Hello.txt),这与Boiethios先生的回答不同。
【讨论】:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
string filename = "/tmp/filename.txt";
int main() {
std::ofstream o(filename.c_str());
o << "Hello, World\n" << std::endl;
return 0;
}
这是我必须做的,以便使用文件名的变量而不是常规字符串。
【讨论】:
使用c方法
FILE *fp =fopen("filename","mode");fclose(fp);mode 表示 a 用于追加 r 阅读,w 写作
/ / using ofstream constructors.
#include <iostream>
#include <fstream>
std::string input="some text to write"
std::ofstream outfile ("test.txt");
outfile <<input << std::endl;
outfile.close();
【讨论】:
/*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 文件夹中创建。
【讨论】: