In C++ is there a way to go to a specific line in a text file?

Loop your way there. #include <fstream> #include <limits> std::fstream& GotoLine(std::fstream& file, unsigned int num){ file.seekg(std::ios::beg); for(int i=0; i < num – 1; ++i){ file.ignore(std::numeric_limits<std::streamsize>::max(),’\n’); } return file; } Sets the seek pointer of file to the beginning of line num. Testing a file with the following content: 1 2 3 4 5 6 7 8 … Read more

How to read a file line by line or a whole text file at once?

You can use std::getline : #include <fstream> #include <string> int main() { std::ifstream file(“Read.txt”); std::string str; while (std::getline(file, str)) { // Process str } } Also note that it’s better you just construct the file stream with the file names in it’s constructor rather than explicitly opening (same goes for closing, just let the destructor … Read more

Getting a FILE* from a std::fstream

The short answer is no. The reason, is because the std::fstream is not required to use a FILE* as part of its implementation. So even if you manage to extract file descriptor from the std::fstream object and manually build a FILE object, then you will have other problems because you will now have two buffered … Read more

mmap() vs. reading blocks

I was trying to find the final word on mmap / read performance on Linux and I came across a nice post (link) on the Linux kernel mailing list. It’s from 2000, so there have been many improvements to IO and virtual memory in the kernel since then, but it nicely explains the reason why … Read more

c++ open file in one line

You can use the constructor to specify the filename: ifstream inputFile(“data.txt”); See the details for std::basic_ifstream (constructor). explicit basic_ifstream( const char* filename, std::ios_base::openmode mode = ios_base::in ); First, performs the same steps as the default constructor, then associates the stream with a file by calling rdbuf()->open(filename, mode | std::ios_base::in) (see std::basic_filebuf::open for the details on … Read more