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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File input help. fstream

Status
Not open for further replies.

mikeeeblue

Programmer
May 26, 2005
7
GB
Hey all

I want to read all the characters from a txt file into a char array, however the problem is is with the code i am currently using i need to set the array size of the char array and if the file has more characters in than the amount of elements declared in the char array then some of the file wont be read in. Do you know how to solve this problem? Thanks :) btw im using windows

char s[2000];
fstream file_op("c:/test.txt",ios::in);
while(!file_op.eof())
{
file_op.getline(s,2000);
cout <<s;
} file_op.close();
cout <<endl;
 
Use the string class that grows automatically. If for some reason you cannot use the string class, then you must use dynamic allocation so that you can reallocate your array if it is not big enough.

By the way, you should not use eof() to control the while loop like you did. change it to:
Code:
while (file_op.getline(s,2000))
or if you convert to strings:
Code:
while(getline(file_op, s))
 
2-3 options.

1. if you insist on using fstream, move the file pointer to the end of the file and count how many bytes there are. create an array of that size.

2. a better way to do what i said above is:
file.seekg(0, ios::end);
int size = file.tellg();
file.seekg(0, ios::beg);

so your file pointer is at the beginning of the file when you open it. move the pointer to teh end (first line of code above). use tellg to get the current position in the file. this is the size of your file in bytes. then finally move the file pointer back to the beginning of the file so you can start reading.

3. use MFCs createfile, readfile etc. there is a function that tells you the size of the file. create teh array of that size.

recommend you use option 2 or 3. if you're using mfc, go with 3.
 
Hi guys, thanks for your help :)

this is now the code


string s;
fstream file_op("c:/another.txt",ios::in);
while(getline(file_op, s))
cout << s << endl;

however i seem to have a problem with the last line, it wont compile and gives me the error:

error C2679: binary '<<' : no operator defined which takes a right-hand operand of type 'class std::basic_string<char,struct std::char_traits<char>,class std::allocator<ch
ar> >' (or there is no acceptable conversion)

any ideas? thanks again
 
I have seen that error when I forgot to #include <string>.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top