C++ Files writing and reading

Write Files

Streams are objects (class) that allow us to write and read data. We can use the stream library in std::fstream to help us. Consider the following code to write to a file.

Read Files

Reading files works similar to writing files. The ifstream is an input files stream that we are going to use in our case. Consider the following example, code, and result from the console.

Let us firstly create a text.txt file with the above input.
  • If we want to read the string until we reach the first space, we can simply use >> operator.
  • If we want to read the file text line by line, we can use the .getline() method in the fstream.
  • If we want to read all the text content inside the files, we have to use a while operation together with .getline(), as well as a method called .eof() in fstream, where .eof() stands for “end of file” and it returns a bool type to check if the file is reached to the end.
The result is exactly what we expected from the code above.

Conclusion

I have mentioned ways to read and write to files in C++ in short with examples. Soon I will also further talk about more files operation in C++ like what I mentioned at the very beginning.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kevin Cheung

Kevin Cheung

𝑾𝒉𝒂𝒕 𝑰 𝒄𝒂𝒏𝒏𝒐𝒕 𝒄𝒓𝒆𝒂𝒕𝒆, 𝑰 𝒅𝒐 𝒏𝒐𝒕 𝒖𝒏𝒅𝒆𝒓𝒔𝒕𝒂𝒏𝒅. . An ordinary developer records his life and learning progress.