Write files in cpp

How to read and write to a text file in C++?

Hey everyone, I have just started to learn C++ and I wanted to know how to read and write to a text file. I have seen many examples but they have all been hard to understand/follow and they have all varied. I was hoping that someone here could help. I am a total beginner so I need clear instructions. Here is an example of what i’m trying to do:

#include #include using namespace std; string usreq, usr, yn, usrenter; int start () < cout > yn; if (yn == "y") < ofstream iusrfile; ofstream ousrfile; iusrfile.open("usrfile.txt", "w"); iusrfile >> usr; cout > usrenter; if (usrenter == usr) < start (); >> else < cout return 0; > 

3 Answers 3

declare input file stream:

declare output file stream:

if you want to use variable for a file name, instead of hardcoding it, use this:

string file_name = "my_file.txt"; ifstream in2(file_name.c_str()); 

reading from file into variables (assume file has 2 int variables in):

int num1,num2; in >> num1 >> num2; 

or, reading a line a time from file:

string line; while(getline(in,line)) < //do something with the line >

write variables back to the file:

Default c++ mechanism for file IO is called streams. Streams can be of three flavors: input, output and inputoutput. Input streams act like sources of data. To read data from an input stream you use >> operator:

istream >> my_variable; //This code will read a value from stream into your variable. 

Operator >> acts different for different types. If in the example above my_variable was an int, then a number will be read from the strem, if my_variable was a string, then a word would be read, etc. You can read more then one value from the stream by writing istream >> a >> b >> c; where a, b and c would be your variables.

Output streams act like sink to which you can write your data. To write your data to a stream, use

Читайте также:  Тег разрыва строки html

As with input streams, you can write several values to the stream by writing something like this:

Obviously inputoutput streams can act as both.

In your code sample you use cout and cin stream objects. cout stands for console-output and cin for console-input . Those are predefined streams for interacting with default console.

To interact with files, you need to use ifstream and ofstream types. Similar to cin and cout , ifstream stands for input-file-stream and ofstream stands for output-file-stream .

Your code might look like this:

#include #include using namespace std; int start() < cout int main () < string usreq, usr, yn, usrenter; cout > yn; if (yn == "y") < ifstream iusrfile; ofstream ousrfile; iusrfile.open("usrfile.txt"); iusrfile >> usr; cout > usrenter; if (usrenter == usr) < start (); >> else < cout return 0; > 

For further reading you might want to look at c++ I/O reference

Источник

Write files in cpp

Потоки для работы с текстовыми файлами представляют объекты, для которых не задан режим открытия ios::binary .

Запись в файл

Для записи в файл к объекту ofstream или fstream применяется оператор
#include #include int main() < std::ofstream out; // поток для записи out.open("hello.txt"); // открываем файл для записи if (out.is_open()) < out out.close(); std::cout

Здесь предполагается, что файла «hello.txt» располагается в одной папке с файлом программы. Данный способ перезаписывает файл заново. Если надо дозаписать текст в конец файла, то для открытия файла нужно использовать режим ios::app :

std::ofstream out("hello.txt", std::ios::app); if (out.is_open()) < out out.close();

Чтение из файла

Если надо считать всю строку целиком или даже все строки из файла, то лучше использовать встроенную функцию getline() , которая принимает поток для чтения и переменную, в которую надо считать текст:

#include #include #include // для std::getline int main() < std::string line; std::ifstream in("hello.txt"); // окрываем файл для чтения if (in.is_open()) < while (std::getline(in, line)) < std::cout > in.close(); // закрываем файл >

Также для чтения данных из файла для объектов ifstream и fstream может применяться оператор >> (также как и при чтении с консоли):

#include #include #include struct Point < Point(double x, double y): x, y <> double x; double y; >; int main() < std::vectorpoints< Point, Point, Point>; std::ofstream out("points.txt"); if (out.is_open()) < // записываем все объекты Point в файл for (const Point& point: points) < out > out.close(); std::vector new_points; std::ifstream in("points.txt"); // окрываем файл для чтения if (in.is_open()) < double x, y; while (in >> x >> y) < new_points.push_back(Point); > > in.close(); for (const Point& point: new_points) < std::cout >

Здесь вектор структур Point записывается в файл.

Читайте также:  Создать массив python random

for (const Point& point: points)

При чем при записи значений переменных файл они отделяются пробелом. В итоге будет создаваться файл в формате

Используя оператор >>, можно считать последовательно данные в переменные x и y и ими инициализировать структуру.

double x, y; while (in >> x >> y) < new_points.push_back(Point); >

Но стоит отметить, что это ограниченный способ, поскольку при чтении файла поток in использует пробел для отделения одного значения от другого и таким образом считывает эти значения в переменные x и y. Если же нам надо записать и затем считать строку, которая содержит пробелы, и какие-то другие данные, то такой способ, конечно, не сработает.

Источник

Create a text file and write to it in C++?

please edit your post and add the exact error message you have. Also the complete code (properly formatted, with the headers) would probably help.

@user: Where does FileStream come from? Why are you creating two streams? Why are you creating your streams dynamically? Are you a Java programmer that switched to C++?

3 Answers 3

You get an error because you have fs declared twice in two different ways; but I wouldn't keep anything of that code, since it's a strange mix of C++ and C++/CLI.

In your question is not clear whether you want to do standard C++ or C++/CLI; assuming you want "normal" C++, you should do:

#include #include // . int main() < // notice that IIRC on modern Windows machines if you aren't admin // you can't write in the root directory of the system drive; // you should instead write e.g. in the current directory std::ofstream fs("c:\\k.txt"); if(!fs) < std::cerrfs

Notice that I removed all the new stuff since very often you don't need it in C++ - you can just allocate the stream object on the stack and forget about the memory leaks that were present in your code, since normal (non GC-managed) pointers aren't subjected to garbage collection.

Читайте также:  About struts in java

Here are examples for both native and managed C++:

Assuming you are happy with a native solution the following works just fine:

 fstream *fs =new fstream(filename,ios::out|ios::binary); fs->write("ghgh", 4); fs->close(); delete fs; // Need delete fs to avoid memory leak 

However, I would not use dynamic memory for the fstream object (i.e. the new statement and points). Here is the new version:

 fstream fs(filename,ios::out|ios::binary); fs.write("ghgh", 4); fs.close(); 

EDIT, the question was edited to request a native solution (originally it was unclear), but I will leave this answer as it may be of use to someone

If you are looking for a C++CLI option (for managed code), I recommend using StreamWriter instead of FileStream. StreamWriter will allow you work with Managed Strings. Note that delete will call the Dispose method on the IDisposable interface and the Garbage Collected will release the memory eventually:

StreamWriter ^fs = gcnew StreamWriter(gcnew String(filename)); fs->Write((gcnew String("ghgh"))); fs->Close(); delete fs; 

Источник

Оцените статью