Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reading from files

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
My humble thanks in advance.

Coming from easier languages like java, I am used to the idea of being able to read characters in from a file and then have the whole file in memory in a big string or byte array. But in c++ I've only managed cumbersome, round-about ways of doing this.

I tried reading characters with an ifstream using getline (see below), but in every move through the loop, fin always reads in characters in at the beginning of the character array. So I have the ridiculous setup below with an offset counter to copy the values from a little input array (c) to the appropriate position in a big storage array (content). There has to be an easier way. I know that this is pretty bad but please suggest something better.

#include <fstream.h>
int main()
{
char c[100];
char content[10000];
int counter = 0;
ifstream fin(&quot;file.cpp&quot;);
if (fin)
{
while(!fin.eof())
{
fin.getline(c, sizeof(c));
for (int i=0; i<strlen(c); i++)
content[i+counter] = c[ i ];
counter += strlen(c);
}
}
cout << content;
return 0;
}
 
If you want to read each character in from the file you might try something like:
Code:
fin >> c;
// Process c into content, etc.

But if you are trying to read the whole thing into memory try:
Code:
fin.read(content, 10000);

The problem will be that big files may not fit into memory. One word pf warning, I haven't tested these but I'm pulling these from my memory (which tends to be faulty).
James P. Cottingham
 
Great thanks JPC!
that worked. Now I have:

#include <fstream.h>
int main()
{
char content[10000];
char fileName[] = &quot;file.cpp&quot;;
ifstream fin(fileName);
if (fin) fin.read(content, sizeof(content));
cout << content;
return 0;
}

Which works fine and the char array content holds the file content.

Now suppose I want to copy that char array to a standard string object. How would I do that?

Any help appreciated.
 
The easiest way is to do something like:
Code:
String strContent = content;

Going the other way is the kicker. You will need c_str. There are possible memory violations with this but most of the time it works.
Code:
content = strContent.c_str();

Don't forget to include the proper string header. Again, I'm doing this from memory and I may have forgotten something important.
James P. Cottingham
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top