473,406 Members | 2,217 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

File handling in C++

Hello everyone. I find it amazing how in C++ that reading in files still
more or less requries usage of char * type. I know there's getline to use
std::string, but the basic_stream::get methods don't work with std::string.
I would like to create a function perhaps something like:

void read(std::string &s, int numBytes);

where the user passes in s to have numBytes of data read from a file into s.
Well, this would require me to do a thing like allocate memory of char bytes
and then do a copy over to the string. So, for this reason, I find myself
sticking to doing the C thing and using FILE pointers and all because to me,
it seems like a waste to read into a char array, then copy over to
std::string, so to avoid that copy, I just do the C thing.

So, am I unaware of a way around this problem? Thanks in advance.

John

Jul 22 '05 #1
4 2814
John Ruiz wrote:
Hello everyone. I find it amazing how in C++ that reading in files still
more or less requries usage of char * type. I know there's getline to use
std::string, but the basic_stream::get methods don't work with std::string.
I would like to create a function perhaps something like:

void read(std::string &s, int numBytes);

where the user passes in s to have numBytes of data read from a file into s.
Well, this would require me to do a thing like allocate memory of char bytes
and then do a copy over to the string.
How else would such a function work, even if it were part of the
standard library? Even with a bit of memcpy magic, how would you get
around copying the text out of the I/O system's buffer? Would it be
more efficient to use unbuffered input?
So, for this reason, I find myself
sticking to doing the C thing and using FILE pointers and all because to me,
What does that accomplish? Aren't you still working with C-style
strings? What problem have you solved or avoided?
it seems like a waste to read into a char array, then copy over to
std::string, so to avoid that copy, I just do the C thing.
You didn't have to do that copy when you were using std::istream,
either. You just chose to do so because you liked std::string. How has
that changed? Does mixing the standard library with the core language
make you feel bad?
So, am I unaware of a way around this problem? Thanks in advance.


Why not write your own implementation of "read" to use std::string if
you don't like null-terminated character arrays? You could append one
character at a time, as needed. If you're willing to spare a bit of
space, you could buffer the input yourself to get more characters with
each call to std::istream::read. The buffer even could be automatic, so
it wouldn't take up space unless your custom "read" function actually
were used. Wait a minute, let me go try something.

Ok, here you go. This isn't production code, it's just something I
whipped up; so, don't berate me if you see something you like. Do feel
free to point it out, though.

#include <cstddef>
#include <istream>
#include <string>

namespace IO
{
typedef std::istream Istream;
typedef std::string String;
typedef std::size_t Size;
/* Read as many chars as possible (up to given maximum) from an
* input stream and append them to a string. Return the number of
* characters successfully read.
*/
Size read( Istream&, String&, Size maximum_quantity_of_chars_to_read );
}

#include <iostream>

int main( )
{
std::string s;

IO::read( std::cin, s, 10 );

std::cout << s << '\n';
}

namespace IO
{
Size const buffer_size = 1024;

typedef char Buffer[ buffer_size ];
}

IO::Size IO::read( Istream& input, String& s, Size max_chars )
{
Size num_chars_read = 0; // To be returned.
Buffer buffer;

for( Size full_buffers_to_read = max_chars / buffer_size;
input and full_buffers_to_read;
--full_buffers_to_read )
{
input.read( buffer, buffer_size );
s.append( buffer, input.gcount( ) );
num_chars_read += input.gcount( );
}

Size chars_still_wanted = max_chars % buffer_size;

if( input and chars_still_wanted )
{
input.read( buffer, chars_still_wanted );
s.append( buffer, input.gcount( ) );
num_chars_read += input.gcount( );
}

return num_chars_read;
}

Jul 22 '05 #2
Jeff Schwab wrote:
This isn't production code, it's just something I
whipped up; so, don't berate me if you see something you
don't
like. Do feel free to point it out, though.


Jul 22 '05 #3

"John Ruiz" <to*********@hotmail.com> wrote in message
news:K6****************@fe03.usenetserver.com...
Hello everyone. I find it amazing how in C++ that reading in files still
more or less requries usage of char * type. I know there's getline to use
std::string, but the basic_stream::get methods don't work with std::string. I would like to create a function perhaps something like:

void read(std::string &s, int numBytes);

where the user passes in s to have numBytes of data read from a file into s. Well, this would require me to do a thing like allocate memory of char bytes and then do a copy over to the string. So, for this reason, I find myself
sticking to doing the C thing and using FILE pointers and all because to me, it seems like a waste to read into a char array, then copy over to
std::string, so to avoid that copy, I just do the C thing.
Thaink about what you are saying here. You are preferring ugly code just
because of a percieved inefficiency in copying some bytes (have you ever
timed it to see how many extra fractions of a millisecond it takes). Write
your read function and forget about 'inefficiency'. The single biggest
inefficiency in the whole computing industry is poor quality code.

So, am I unaware of a way around this problem? Thanks in advance.

You could read into a vector<char>. It's pretty rare to want to read a fixed
number of bytes of *text*, so maybe you shouldn't be using string at all.
John


john
Jul 22 '05 #4
"John Harrison" <jo*************@hotmail.com> wrote in message
news:c1*************@ID-196037.news.uni-berlin.de...

"John Ruiz" <to*********@hotmail.com> wrote in message
news:K6****************@fe03.usenetserver.com...
Hello everyone. I find it amazing how in C++ that reading in files still more or less requries usage of char * type. I know there's getline to use std::string, but the basic_stream::get methods don't work with std::string.
I would like to create a function perhaps something like:

void read(std::string &s, int numBytes);

where the user passes in s to have numBytes of data read from a file into s.
Well, this would require me to do a thing like allocate memory of char bytes
and then do a copy over to the string. So, for this reason, I find

myself sticking to doing the C thing and using FILE pointers and all because to

me,
it seems like a waste to read into a char array, then copy over to
std::string, so to avoid that copy, I just do the C thing.


Thaink about what you are saying here. You are preferring ugly code just
because of a percieved inefficiency in copying some bytes (have you ever
timed it to see how many extra fractions of a millisecond it takes). Write
your read function and forget about 'inefficiency'. The single biggest
inefficiency in the whole computing industry is poor quality code.

So, am I unaware of a way around this problem? Thanks in advance.


You could read into a vector<char>. It's pretty rare to want to read a

fixed number of bytes of *text*, so maybe you shouldn't be using string at all.
John


john


Hi guys. Thanks for the input and of course, I'm not going to berate your
code. This is only a forum. Later, and I'll be posting more questions I'm
sure later on.

Jul 22 '05 #5

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

Similar topics

9
by: Hans-Joachim Widmaier | last post by:
Hi all. Handling files is an extremely frequent task in programming, so most programming languages have an abstraction of the basic files offered by the underlying operating system. This is...
1
by: Sean W. Quinn | last post by:
Hey folks, I have a question regarding file handling, and the preservation of class structure. I have a class (and I will post snippets of code later in the post) with both primitive data...
5
by: John Douglass | last post by:
I'm fairly new to doing involved file i/o and I came across something weird with a program I'm writing (modifying MIDI data, if it makes any difference). With some input files, when I modify data...
8
by: Gabe Moothart | last post by:
Hi, I'm writing a windows service which interacts with a separate process. Basically, it calls a process which creates a file, and then my service reads that file. The problem is, the external...
14
by: Al Smith | last post by:
I need help in implementing proper error handling. I am trying to upload a file based on the sample code below. The code works well except if the file selected is too big. I do know about the...
1
by: laredotornado | last post by:
Hi, I'm using PHP 4.4.4 on Apache 2 on Fedora Core 5. PHP was installed using Apache's apxs and the php library was installed to /usr/local/php. However, when I set my "error_reporting"...
5
by: Digital Puer | last post by:
I fixed a bug today that went against my intuition. I am on Linux. I had a class that fopen'ed some files. When I called delete on these objects, I expected that the files would be closed...
19
by: rmr531 | last post by:
First of all I am very new to c++ so please bear with me. I am trying to create a program that keeps an inventory of items. I am trying to use a struct to store a product name, purchase price,...
5
AdrianH
by: AdrianH | last post by:
Assumptions I am assuming that you know or are capable of looking up the functions I am to describe here and have some remedial understanding of C++ programming. FYI Although I have called...
5
by: kailashchandra | last post by:
I am trying to upload a file in php,but it gives me error msg please Help me? My Code is like below:- i have one php file named upload.php and i have another html file named upload.html and...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
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...
0
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...

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.