I'm currently writing a C++ program that reads in a text file and outputs certain things. So far, my program can read in the file then create a brand new file that contains the info from the first file (basically the new file is a duplicate of the first). Does anyone know how would I check for certain words or characters in the file? For example (several lines from the initial file):
SCALE3 0.0000000 0.000000 1.000000 0.000000...............
ATOM 1 N LYS A 2 -1.166 -1.878 1.710 1.00 0.00 N
ATOM 2 CA LYS A 2 -0.110 -1.837 0.660 1.00 0.00 C
These are three lines from the initial txt file. How would I do a check for the lines containing the word "ATOM" and print ONLY those lines to the output txt file. PLEASE HELP!!!
C++ Input, output programming. PLEASE HELP!!!?
first you need unformatted input. Assuming you're using an fstream, you could use either:
c=Myfile.get();
or Myfile.get(c);
(You can also get strings but that would be distracting.)
Now we have input we can woory about what we are going to do. Let's have an integer called State (as in state machines). Initialize it to 0.
while Myfile.good(){
c=Myfile.get();
if (c=='\n')
parse the next 4 letters for ATOM. If so, back up 4, set State to 2 and
while (State==2){
c=Myfile.get();
Outfile %26lt;%26lt; c;
if (c=='\n') State=0;
}
EDIT: other functions worth checking out on the fstream page cited below include putback(), which will rewind your file one char. Definitely use it at the end of the State==2 loop.
Of course if you are using FILE *InFile and fopen, fclose, and so forth from stdio.h (cstdio) you have fgetc(), and fread() for unformatted input, and fputc() and frwrite() for output.
fgetpos(FILE, *int) will put the position your position in a file into an integer -- useful when you want to fsetpos(FILE, *int) (okay, so they're not ints, they're fpos_t's.) In this case you would want to reset the file so you read atom, and you would want to reset it after getting a newline in State 2, which allows you to vet the next line in your text file.
(if you don't then in the above sample the second line with ATOM on it won't be read into the new file because when it would look for the A it would get a T).
That should work.
As you can tell I've been answering this when I'm tired. Sorry.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment