Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating files in C++

Tags:

c++

file-io

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?

like image 851
Uffo Avatar asked Jan 25 '09 19:01

Uffo


People also ask

How to create file and write data into file in C?

Step by step descriptive logic to create a file and write data into file. Declare a FILE type pointer variable to store reference of file, say FILE * fPtr = NULL;. Create or open file using fopen() function. Input data from user to write into file, store it to some variable say data. C provides several functions to perform IO operation on file.

What is a file in C programming?

This chapter cover how C programmers can create, open, close text or binary files for their data storage. A file represents a sequence of bytes, regardless of it being a text file or a binary file.

How do I create a file from a specific path?

The File.Create () method takes a file name with the full path as its first and required parameter and creates a file at the specified location. If same file already exists at the same location, this method overwrites the file.

What are the examples of C program?

C File Examples 1 C program to read name and marks of n number of students and store them in a file. ... 2 C program to read name and marks of n number of students from and store them in a file. ... 3 C program to write all the members of an array of structures to a file using fwrite (). Read the array from the file and display on the screen.


2 Answers

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.

like image 113
James Thompson Avatar answered Sep 20 '22 05:09

James Thompson


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.

like image 33
Boiethios Avatar answered Sep 19 '22 05:09

Boiethios