Sign in to follow this  
Followers 0
JohnOne

Reading a file C++ (solved)

9 posts in this topic

#1 ·  Posted (edited)

I am trying to read a file and output/return it all at once.

I was expecting to do this with this code...

ifstream myReadFile;
        myReadFile.open(sFile);
        char output[40960];
        if (myReadFile.is_open())
     {
            while (!myReadFile.eof())
         {
                myReadFile >> output;
          
                }
            }
  myReadFile.close();
  cout<<output;

But (probably unsurprising to others) it does not do as I expected.

It outputs (returns in my dll) just the last line of the file, and furthermore

ignores all spaces.

I'd appreciate it if someone would be so kind as to steer me toward

a solution.

Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites



#5 ·  Posted (edited)

Still cannot get my head around this, I have tried 2 approaches, both of which hang.

ifstream myReadFile;
        myReadFile.open(sFile);
  char output[40960];
  char tmp[1024];
  if (myReadFile.is_open())
     {
            while (!myReadFile.eof())
         {
    myReadFile.getline(tmp,1024); // hangs
                //myReadFile >> tmp; // works but strips white space
    //myReadFile >> noskipws >> tmp; // hangs
    strcat(output,tmp); 
            }
        }
  myReadFile.close();
  cout<<output;

EDIT:

Scrap that, as you suggested .get() works, .getline() does not.

Thanks.

One question, when using get(), is this reading one char at a time?

Edited by JohnOne

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

This works for me:

#include <iostream>

#include <fstream>

#include <String>



using namespace std;



int main()

{

    ifstream myReadFile;



    string sFile = "C:UsersMatthewDesktoptest.txt";



    myReadFile.open(sFile.c_str(), ios::in);



    if (myReadFile.is_open())

    {

        string output;



        while (myReadFile.good())

        {

            output += myReadFile.get();

        }



        myReadFile.close();



        cout << output;

    }



    return 0;

}

Edited by LaCastiglione

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0