File Handling

B

ben

Hi guyz,
Say a line "abcdef..." is written to a file.
The file is created like this :
ofstream fout;
fout.open("temp.dat");
fout<<str;//str is string with contents like abcd....
fout.close();

Now i open the file for reading using

ifstream fin;
fin.open("temp.dat");

The pointer will be by default positioned to the 0th byte of the
file(beginning of the file).

Now i want to find the letter 't' or say 'w' in that string.

The problem is i wont be knowing what is the size of the
string and where it ends.(The string is not null terminated.There might
be whitespace at the end).

I tried out all possible functions like fin.peek(),fin.ignore(MAX,'\n')
and so on but in vein.

Can anyone suggest a way out?(I can't use commands like find)
How do i find out what is stored in nth byte of the file?

bye,
ben
 
P

Peter Jansson

ben said:
Now i want to find the letter 't' or say 'w' in that string.

The problem is i wont be knowing what is the size of the
string and where it ends.(The string is not null terminated.There might
be whitespace at the end).

How about this:

ifstream fin("temp.dat");
std::string line;
std::getline(fin,line); // Reads until widen('\n') or until end of file.
CallYourMethodOfChoiceHereToFindTheCharacterTOrWhatever(line);

Regards,
Peter Jansson
http://www.jansson.net/
 
B

ben

well my problem got solved like this:
ifstream fin("temp.dat")
char c;
while(c !=' * ')
{
fin>>c;
}
..
..
Thanks anyway.
 
K

Kurt Stutsman

ben said:
well my problem got solved like this:
ifstream fin("temp.dat")
char c;
while(c !=' * ')
{
fin>>c;
}
.
.
Thanks anyway.

There are a few things wrong with that code. For one, c is left uninitialized
and then later compared to a value. Also, your character literal ' * ' has 3
characters in it. You're also not checking for EOF. This is probably better
(maybe):

ifstream fin("temp.dat");
char c;
while(fin >> c) {
if(c == '*')
break;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,291
Messages
2,571,455
Members
48,132
Latest member
KatlynC08

Latest Threads

Top