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?

8 Answers 8

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.

7
  • 6
    Not to mention that std::endl also writes the correct platform specific newline character string. Jan 25, 2009 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
    – Iraimbilanja
    Jan 25, 2009 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, 2009 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, 2009 at 20:28
  • 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. Jun 23, 2010 at 10:07
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.

3
  • how change from ( ) to { } make it create the file and close ?
    – Jackt
    Sep 17, 2021 at 21:23
  • @Jackt It's not () vs {}, it's just due to the destructor running. But you're right, there is an error. I've reverted to a previous revision, there has been a faulty edition.
    – Boiethios
    Sep 18, 2021 at 7:43
  • even better, tnx!
    – Jackt
    Sep 19, 2021 at 1:42
13
#include <iostream>
#include <fstream>

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

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

  return 0;
}
11
  • 17
    The \n in the string is redundant when using std::endl. Jan 25, 2009 at 19:20
  • The return 0; in the function is redundant when using "int main()"
    – Iraimbilanja
    Jan 25, 2009 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.
    – Iraimbilanja
    Jan 25, 2009 at 19:22
  • 4
    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, 2009 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, 2009 at 20:10
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.

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.

2
  • 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. Sep 29, 2018 at 8:30
  • caveat: if the raw "Hello.txt" was replaced by an already existing variable, this wouldn't compile for MSVC17. Jan 31, 2019 at 0: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.

-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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.