98

I want to create a file using C++, but I have no idea how to do it. For example I want to create a text file named Hello.txt.

Can anyone help me?

Yi Jiang
  • 49,435
  • 16
  • 136
  • 136
Uffo
  • 9,628
  • 24
  • 90
  • 154

8 Answers8

162

One way to do this is to create an instance of the ofstream class, and use it to write to your file. Here's a link to a website that has some example code, and some more information about the standard tools available with most implementations of C++:

ofstream reference

For completeness, here's some example code:

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

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

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

outfile.close();

You want to use std::endl to end your lines. An alternative is using '\n' character. These two things are different, std::endl flushes the buffer and writes your output immediately while '\n' allows the outfile to put all of your output into a buffer and maybe write it later.

James Thompson
  • 46,512
  • 18
  • 65
  • 82
  • 6
    Not to mention that std::endl also writes the correct platform specific newline character string. – Grant Limberg Jan 25 '09 at 19:27
  • 6
    To Limberg: thats wrong. "endl: Effects: Calls os.put(os.widen('\n')), then os.flush()" -- C++ standard, 27.6.2.7/1 –  Jan 25 '09 at 20:26
  • 14
    @Grant Limberg: '\n' also writes the correct platform specific newline--it's translated as appropriate by the ostream internals. – Drew Hall Jan 25 '09 at 20:27
  • 3
    @James Thompson: The only reason to use std::endl is if you really need to guarantee that the buffer is flushed to the file IMMEDIATELY. Otherwise, it's a needless pessimization (file i/o is very expensive!). – Drew Hall Jan 25 '09 at 20:28
  • @Grant Limberg: http://en.wikipedia.org/wiki/Newline#Newline_in_programming_languages – cic Jan 25 '09 at 20:34
  • 2
    When using ofstream for writing to a file, then no file locking is implemented. It is possible for others to read the half-written file, or for others to open another ofstream and write simultaneously. – Rolf Kristensen Jun 23 '10 at 10:07
  • important note: file will not be created if folder does not exist, e.g. std::ofstream("testDir/test.txt") will only work if "testDir" folder exists; – OverInflatedWalrus Jul 27 '22 at 14:22
42

Do this with a file stream. When a std::ofstream is closed, the file is created. I prefer the following code, because the OP only asks to create a file, not to write in it:

#include <fstream>

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

The stream is destroyed right after its creation, so the stream is closed inside the destructor and thus the file is created.

Boiethios
  • 38,438
  • 19
  • 134
  • 183
13
#include <iostream>
#include <fstream>

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

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

  return 0;
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
  • 17
    The \n in the string is redundant when using std::endl. – Greg Hewgill Jan 25 '09 at 19:20
  • The return 0; in the function is redundant when using "int main()" –  Jan 25 '09 at 19:21
  • True, but I like to explicitly flush the output buffer. – Sean Bright Jan 25 '09 at 19:21
  • The #include is redundant when using std::ofstream. –  Jan 25 '09 at 19:21
  • 3
    endl does more than flush: it outputs a newline too. So either print \n then std::flush, or just use std::endl. –  Jan 25 '09 at 19:22
  • 5
    streams get flushed on destruction, so the std::endl is completely superfluous in this case. However, the "return 0" is definitely NOT redundant. It was a common case in C to imply "return 0", but that is not true with C++. – Tom Jan 25 '09 at 19:53
  • 1
    @Tom: basic.start.main: "If control reaches the end of main without encountering a return statement, the effect is that of executing: return 0;". – cic Jan 25 '09 at 20:10
  • also std::endl is not superfluous. it outputs a '\n' before flushing. omitting it will result in only one trailing newline instead of two. oO – Johannes Schaub - litb Jan 25 '09 at 20:26
  • litb no one event wanted 2 newlines, sean thought he was only outputting one –  Jan 25 '09 at 20:28
  • Thanks for all the feedback, both positive and negative. You are all absolutely correct, I included an unnecessary std::endl and #include. My personal preference regarding the return statement is to always include them, even in methods returning void. – Sean Bright Jan 26 '09 at 01:21
  • +1 for noting that ofstream is automatically closed when it goes out of scope! – Mr.Ree Jan 26 '09 at 08:49
4
#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;
}

This is what I had to do in order to use a variable for the filename instead of a regular string.

sajjadG
  • 2,546
  • 2
  • 30
  • 35
Angelo
  • 51
  • 1
4

Here is my solution:

#include <fstream>

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

File (Hello.txt) is created even without ofstream name, and this is the difference from Mr. Boiethios answer.

  • Ladies, Gentlemen, please let me say you that when someone asks what to do for get some result, and reads an answer, thinks that EVERYTHING in answer IS NEEDED for get this result. For this, answer should include only WHAT IS NEEDED for get the desired result. Regards. – George Theodosiou Sep 29 '18 at 08:30
  • caveat: if the raw "Hello.txt" was replaced by an already existing variable, this wouldn't compile for MSVC17. – kayleeFrye_onDeck Jan 31 '19 at 00:29
1

If you want to create a file with some content and don't need to deal with the ofstream after that you can simply write:

#include <fstream>

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

no need to manually close the file, deal with variables, etc. The file is created, written, and closed in the same line.

Tachi
  • 489
  • 8
  • 16
-1
/*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();
} 

After running the program the file will be created inside the bin folder in your compiler folder itself.

Vinayyy
  • 19
-1

use c methods FILE *fp =fopen("filename","mode"); fclose(fp); mode means a for appending r for reading ,w for writing

   / / 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();