92
votes

I'm in a tutorial which introduces files (how to read from file and write to file)

First of all, this is not a homework, this is just general help I'm seeking.

I know how to read one word at a time, but I don't know how to read one line at a time, or how to read the whole text file.

What if my file contains 1000 words? It is not practical to read entire file word after word.

My text file named "Read" contains the following:

I love to play games
I love reading
I have 2 books

This is what I have accomplished so far:

#include <iostream>
#include <fstream>

using namespace std;
int main (){
   
  ifstream inFile;
  inFile.open("Read.txt");

  inFile >>

Is there any possible way to read the whole file at once, instead of reading each line or each word separately?

9
Reading word by word is only marginally slower than line by line. If you actually need words, then it's better to read words. Read lines if you're dealing with line-oriented data such as CSV file. - user3458
@Arkadiy that is incorrect. For an 100 MiB file, reading line by line will easily take seconds, while reading a block of 4 KiB at a time seconds less than a second. - vallentin
@Vallentin: Given that the streams are all buffered, the actual disk reading is done block by block already. The rest is just manipulating data in memory. - user3458

9 Answers

171
votes

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 do the work).

Further documentation about std::string::getline() can be read at CPP Reference.

Probably the easiest way to read a whole text file is just to concatenate those retrieved lines.

std::ifstream file("Read.txt");
std::string str;
std::string file_contents;
while (std::getline(file, str))
{
  file_contents += str;
  file_contents.push_back('\n');
}  
21
votes

I know this is a really really old thread but I'd like to also point out another way which is actually really simple... This is some sample code:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main() {

    ifstream file("filename.txt");
    string content;

    while(file >> content) {
        cout << content << ' ';
    }
    return 0;
}
5
votes

I think you could use istream .read() function. You can just loop with reasonable chunk size and read directly to memory buffer, then append it to some sort of arbitrary memory container (such as std::vector). I could write an example, but I doubt you want a complete solution; please let me know if you shall need any additional information.

5
votes

Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:

#include<cstdio>
#include<iostream>

using namespace std;

int main(){
   freopen("path to file", "rb", stdin);
   string line;
   while(getline(cin, line))
       cout << line << endl;
   return 0;
}
1
votes

Another method that has not been mentioned yet is std::vector.

std::vector<std::string> line;

while(file >> mystr)
{
   line.push_back(mystr);
}

Then you can simply iterate over the vector and modify/extract what you need/

0
votes

you can also use this to read all the lines in the file one by one then print i

#include <iostream>
#include <fstream>

using namespace std;



bool check_file_is_empty ( ifstream& file){
    return file.peek() == EOF ;
}

int main (){


    string text[256];
    int lineno ;
    ifstream file("text.txt");
    int num = 0;

    while (!check_file_is_empty(file))
    {    
        getline(file , text[num]);
        num++;
    }
    for (int i = 0; i < num ; i++)
    {
        cout << "\nthis is the text in " <<  "line " << i+1 << " :: " << text[i] << endl ;


    }
    
    system("pause");

    return 0;
}

hope this could help you :)

0
votes

hello bro this is a way to read the string in the exact line using this code

hope this could help you !

#include <iostream>
#include <fstream>

using namespace std;


int main (){


    string text[1];
    int lineno ;
    ifstream file("text.txt");
    cout << "tell me which line of the file you want : " ;
    cin >> lineno ; 



    for (int i = 0; i < lineno ; i++)
    {
        
        getline(file , text[0]);

    }   

    cout << "\nthis is the text in which line you want befor  :: " << text[0] << endl ;
    system("pause");

    return 0;
}

Good luck !

0
votes

The above solutions are great, but there is a better solution to "read a file at once":

fstream f(filename);
stringstream iss;
iss << f.rdbuf();
string entireFile = iss.str();
0
votes

The below snippet will help you to read files which consists of unicode characters

CString plainText="";
errno_t errCode = _tfopen_s(&fStream, FileLoc, _T("r, ccs=UNICODE"));
    if (0 == errCode)
    {
        CStdioFile File(fStream);
        CString Line;
        while (File.ReadString(Line))
        {
            plainText += Line;
        }
    }
    fflush(fStream);
    fclose(fStream);

you should always close the file pointer after you read, otherwise it will leads to error