When you are dealing with the inputs in C++, the task of reading a file is important. There are various methods to do this particular task, which are simple and easier, but they don’t provide a high-speed advantage in extracting and reading input from a file. Here is a method that provides you with this advantage while reading a file line by line, i.e., the std::istream::readsome() method in C++.
What is the istream::readsome() Function in C++?
The istream::readsome() function in C++ is a member function of the std::istream class which is used to read the characters present in the input stream without waiting for any more input. You can use it when you have to deal with the non-blocking input operations in C++.
Declaration Syntax:
std::streamsize readsome(char* s, std::streamsize n);
Parameters:
- s: A pointer to the buffer where the data will be stored.
- n: The maximum number of characters to read from the input stream.
Return Value:
- s returns the number of characters that are read.
- If no character is present at that moment, then it returns 0.
Read a File in Chunks Using std::istream::readsome()
The std::istream::readsome() in C++ reads the input stream up to n characters but not necessarily and stores them in an array pointed with s. It reads the raw data already provided into the buffer and stops when the internal buffer runs out of characters. It basically takes two parameters: a pointer referenced to a character array (buffer) where the data will be stored, and an integer that represents the maximum number of characters to read. The std::istream::readsome() does not handle delimiters or whitespace, and also does not format the data in the file.
Example:
File name: sample.txt
Hello, this is a test file.
Happy Coding!
Output:
The code shows that the attached file is opened and read by using the std::istream::readsome() function, and the while loop ensures that the file has been read till the end and prints the output. Then, the file is closed.
Get 100% Hike!
Master Most in Demand Skills Now!
Another Example:
File name: sample.txt
Hello, let’s read this file.
Reading a file line by line is easy.
Output:
The code shows that the attached file is opened and read by using the std::istream::readsome() function, and the while loop ensures that the file has been read till the end and prints the output. Then, the file is closed.
Conclusion
As we have discussed above, by using the std::istream::readsome(), you can easily read data from a file in chunks or parts. Also, this method provides you with high speed in reading the data, but it does not provide the structured parsing. So, understanding the behavior of std::istream::readsome() in C++ with an example helps you to read a file in chunks easily.
Some Other Methods to Read a File Line by Line in C++
- Read from a Binary File in C++
- eof() in C++
- getline() Function in C++
- basic_istream::operator>> in C++
- std::ifstream::get() in C++