473,580 Members | 2,960 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Read text file into std::string.

Does this function need to call eof after the while-loop to be correct?

bool read_file(std:: string name, std::string &s)
{
std::ifstream in(name.c_str() );
if (!in.is_open())
return false;

char c;
std::string str;
while (in.get(c))
str += c;

if (!in.eof())
return false;

s = str;
return true;
}

Thanks.
Jul 23 '05 #1
22 13225
Jason Heyes wrote:
Does this function need to call eof after the while-loop to be correct?

bool read_file(std:: string name, std::string &s)
{
std::ifstream in(name.c_str() );
if (!in.is_open())
return false;

char c;
std::string str;
while (in.get(c))
str += c;

if (!in.eof())
return false;

s = str;
return true;
}


Calling EOF after the loop here is a check to insure that you exited
the loop because you read to the end of the file. There are a few other
reasons that get() might not be able to read a char and return a count
of 0.

Jul 23 '05 #2
Jason Heyes wrote:
Does this function need to call eof after the while-loop to be correct?
Yes.
bool read_file(std:: string name, std::string &s)
{
std::ifstream in(name.c_str() );
if (!in.is_open())
return false;

char c;
std::string str;
while (in.get(c))
str += c;
This loop is _extremely_ slow (or do you want to prove the
impracticality of C++?). Use getline (in, str) instead.

if (!in.eof())
return false;

s = str;
s.swap(str);
return true;
}


Jul 23 '05 #3
Me
> Does this function need to call eof after the while-loop to be correct?

Depends. The stream can terminate that while loop for a number of
reasons including a bad harddrive or an out of memory condition, etc.
If you want to make sure it read all the characters all the way to end
of the file, you have to check if it exited the loop because due to
eof.
bool read_file(std:: string name, std::string &s)
{
std::string str;
<snip>
s = str;


btw, if this is your code, I suggest you do s.swap(str) instead of the
assignment.

Jul 23 '05 #4

"Jason Heyes" <ja********@opt usnet.com.au> wrote in message
news:42******** *************** @news.optusnet. com.au...
Does this function need to call eof after the while-loop to be correct?

bool read_file(std:: string name, std::string &s)
{
std::ifstream in(name.c_str() );
if (!in.is_open())
return false;

char c;
std::string str;
while (in.get(c))
str += c;

if (!in.eof())
return false;

s = str;
return true;
}

Thanks.


Why not extract the file's contents into a container of strings? If you make
the container a member of a class, read_file() and a write_file() could be
member functions of that class with access to the encapsulated container.

There are a number of other ways this could be done. You might overload the
write() member function so it takes a reference to another string container
to write to file, you might choose to use the same filestream to read /
write, etc.

// FileParser.cpp
//
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
#include <stdexcept>

class FileParser
{
// members
const std::string m_filename_;
std::string m_buffer;
std::ifstream m_ifs;
std::ofstream m_ofs;
std::vector<std ::string> m_vs;
public:
// ctor
FileParser(std: :string s)
: m_filename_(s), m_buffer(), m_ifs(), m_ofs(), m_vs() { }
~FileParser() { }

// read() member function
void read() throw(std::exce ption)
{
m_ifs.open(m_fi lename_.c_str() , std::ios::in);
if (!m_ifs)
{
throw std::exception( "error opening file for read().\n");
}
while (std::getline(m _ifs, m_buffer))
{
m_vs.push_back( m_buffer);
}
if (!m_ifs.eof()) // if reason of termination != eof
{
throw std::exception( "error while parsing file.\n");
}
}

// write(...) member function
void write() throw(std::exce ption)
{
m_ofs.open(m_fi lename_.c_str() );
if (!m_ofs)
{
throw std::exception( "error opening file for write().\n");
}
// copy algorithm with ostream_iterato r
std::copy( m_vs.begin(),
m_vs.end(),
std::ostream_it erator<std::str ing>(m_ofs, "\n") );
}

// load(...) member function
void load(std::vecto r<std::string> & r_vs)
{
m_vs.clear();
std::copy(r_vs. begin(), r_vs.end(), std::back_inser ter(m_vs));
}

// display() member function
void display() const
{
std::cout << "\n--- FileParse::disp lay() ---\n\n";
std::copy( m_vs.begin(),
m_vs.end(),
std::ostream_it erator<std::str ing>(std::cout,
"\n") );
}

}; // class FileParser

int main()
{
std::vector<std ::string> vstrings;
vstrings.push_b ack("string 0");
vstrings.push_b ack("string 1");
vstrings.push_b ack("string 2");
vstrings.push_b ack("string 3");
vstrings.push_b ack("string 4");

// FileParser object
FileParser fileparser("fil e.dat");
fileparser.load (vstrings);
fileparser.disp lay();

try
{
fileparser.writ e();

fileparser.read ();
fileparser.disp lay();
}
catch (const std::exception& e)
{
std::cout << "Error:\n";
std::cout << e.what();
}

return 0;

} // main()

/* file.dat

--- FileParse::disp lay() ---

string 0
string 1
string 2
string 3
string 4

*/
Jul 23 '05 #5
"Rapscallio n" <ra********@spa mbob.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
Jason Heyes wrote:

char c;
std::string str;
while (in.get(c))
str += c;


This loop is _extremely_ slow (or do you want to prove the
impracticality of C++?). Use getline (in, str) instead.


Why is the loop slow? Isn't get inlined?

I read that getline needs a count of the number of elements to extract and
an array to store them. It does not take std::string. So how can I use
getline instead of get in this function?
Jul 23 '05 #6


Jason Heyes wrote:
"Rapscallio n" <ra********@spa mbob.com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com.. .
Jason Heyes wrote:

char c;
std::string str;
while (in.get(c))
str += c;


This loop is _extremely_ slow (or do you want to prove the
impracticality of C++?). Use getline (in, str) instead.


Why is the loop slow? Isn't get inlined?

I read that getline needs a count of the number of elements to extract and
an array to store them. It does not take std::string. So how can I use
getline instead of get in this function?


getline(in, str);

This reads the data until it finds either EOF, '\n' or max amount of
data that can be read is read (to check the last you need to see if the
fail bit is set).
It doesn't copy the '\n' (or EOF) into the string but it does extract
it so the code should be:
getline(in, str);
str+= '\n';

Jul 23 '05 #7
Peter Julian wrote:
Why not extract the file's contents into a container of strings? If you make
the container a member of a class, read_file() and a write_file() could be
member functions of that class with access to the encapsulated container.

There are a number of other ways this could be done. You might overload the
write() member function so it takes a reference to another string container
to write to file, you might choose to use the same filestream to read /
write, etc.
Your FileParser is done well but the design is not perfect. Some
remarks are attached. Refactoring the design is recommended.
// FileParser.cpp
//
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <algorithm>
#include <stdexcept>

class FileParser
{
// members
const std::string m_filename_;
std::string m_buffer;
std::ifstream m_ifs;
std::ofstream m_ofs;
These need not be members.

std::vector<std ::string> m_vs;
Use std::list to avoid unnecessary copies of strings (each copy > 16
means dynamic allocation on VC 7.1)
std::vector<std ::string> m_vlist;
public:
// ctor
FileParser(std: :string s)
: m_filename_(s), m_buffer(), m_ifs(), m_ofs(), m_vs() { }
~FileParser() { }

// read() member function
void read() throw(std::exce ption)
{
m_ifs.open(m_fi lename_.c_str() , std::ios::in);
if (!m_ifs)
{
throw std::exception( "error opening file for read().\n");
}
while (std::getline(m _ifs, m_buffer))
{
m_vs.push_back( m_buffer);
m_vlist.resize (m_vlist.size() +1);
m_vlist.back(). swap (m_buffer);
}
if (!m_ifs.eof()) // if reason of termination != eof
{
throw std::exception( "error while parsing file.\n");
}
}

// write(...) member function
void write() throw(std::exce ption)
void write (std::ostream& os) // write to any ostream
{
m_ofs.open(m_fi lename_.c_str() );
if (!m_ofs)
{
throw std::exception( "error opening file for write().\n");
}
// copy algorithm with ostream_iterato r
std::copy( m_vs.begin(),
m_vs.end(),
std::ostream_it erator<std::str ing>(m_ofs, "\n") );
}

// load(...) member function
void load(std::vecto r<std::string> & r_vs)
why this???
{
m_vs.clear();
std::copy(r_vs. begin(), r_vs.end(), std::back_inser ter(m_vs));
} // display() member function
void display() const
friend
std::ostream& operator<< (std::ostream& os, const FileParser& f);
{
std::cout << "\n--- FileParse::disp lay() ---\n\n";
std::copy( m_vs.begin(),
m_vs.end(),
std::ostream_it erator<std::str ing>(std::cout,
"\n") );
}

}; // class FileParser

int main()
{
std::vector<std ::string> vstrings;
vstrings.push_b ack("string 0");
vstrings.push_b ack("string 1");
vstrings.push_b ack("string 2");
vstrings.push_b ack("string 3");
vstrings.push_b ack("string 4");

// FileParser object
FileParser fileparser("fil e.dat");
fileparser.load (vstrings);
fileparser.disp lay();

try
{
fileparser.writ e();

fileparser.read ();
fileparser.disp lay();
}
catch (const std::exception& e)
{
std::cout << "Error:\n";
std::cout << e.what();
}

return 0;

} // main()

/* file.dat

--- FileParse::disp lay() ---

string 0
string 1
string 2
string 3
string 4

*/


Jul 23 '05 #8
Jason Heyes wrote:

Why is the loop slow? Isn't get inlined?
It's inlined probably, but still moves one character at a time
fom the stream and grows the string one element at a time with it.
I read that getline needs a count of the number of elements to extract and
an array to store them. It does not take std::string. So how can I use
getline instead of get in this function?

You didn't read far enough. There's a getline that's not a member
of stream that takes a string.
Jul 23 '05 #9
Ron Natalie wrote:
Jason Heyes wrote:

Why is the loop slow? Isn't get inlined?

It's inlined probably, but still moves one character at a time
fom the stream and grows the string one element at a time with it.


And you think getline does someting else internally?

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
8157
by: Angus Leeming | last post by:
Hello, Could someone explain to me why the Standard conveners chose to typedef std::string rather than derive it from std::basic_string<char, ...>? The result of course is that it is effectively impossible to forward declare std::string. (Yes I am aware that some libraries have a string_fwd.h header, but this is not portable.) That...
11
3630
by: Christopher Benson-Manica | last post by:
Let's say I have a std::string, and I want to replace all the ',' characters with " or ", i.e. "A,B,C" -> "A or B or C". Is the following the best way to do it? int idx; while( (idx=str.find_first_of(',')) >= 0 ) { str.replace( idx, 1, "" ); str.insert( idx, " or " ); }
19
6131
by: Erik Wikström | last post by:
First of all, forgive me if this is the wrong place to ask this question, if it's a stupid question (it's my second week with C++), or if this is answered some place else (I've searched but not found anything). Here's the problem, I have two sets of files, the name of a file contains a number which is unique for each set but it's possible...
6
6601
by: Khuong Dinh Pham | last post by:
How do i read the contents of a xml file and output it to a std::string. Thx in advance
6
11490
by: Nemok | last post by:
Hi, I am new to STD so I have some questions about std::string because I want use it in one of my projects instead of CString. 1. Is memory set dinamicaly (like CString), can I define for example string str1; as a class member and then add text to it. or do I have to specify it's length when defining? 2. How to convert from std::string...
25
31723
by: electrixnow | last post by:
in MS VC++ Express I need to know how to get from one comma delimited text string to many strings. from this: main_string = "onE,Two,Three , fouR,five, six " to these: string1 = "one"
2
5488
by: FBergemann | last post by:
if i compile following sample: #include <iostream> #include <string> int main(int argc, char **argv) { std::string test = "hallo9811111z"; std::string::size_type ret;
84
15825
by: Peter Olcott | last post by:
Is there anyway of doing this besides making my own string from scratch? union AnyType { std::string String; double Number; };
6
2334
by: SpreadTooThin | last post by:
How can I read in two characters from a file into a std::string? the long way: fstream f("myfile.bin", ios::binary | ios:in); // Opened for read binary... unsigned char buffer; buffer = '\0'; f.read(buffer, 2); std::string x(buffer);
0
8132
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7878
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8157
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6533
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5665
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5349
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3806
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2295
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1394
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.