--- pushkar raj <[EMAIL PROTECTED]> wrote:

> Hi everybody,
> 
> I have a text file which contains a sequence of
> characters terminated by newline.
> I need to extract a sequence of character from the
> file until i encounter underscore character.
> The moment I encounter underscore character, I need
> to move to the next line.
> This process is to be repeated till I reach the end
> of file.
> 
> The code that I have been trying is given below.....
> The problem with this code is that the loop doesn't
> terminate.
> 
> #include<stdio.h>
> #include<conio.h>
> #include<stdlib.h>
> 
> int main()
> {
>  FILE *fp1, *fp2;
>  char ch;
>  clrscr();
>  fp1=fopen("11.txt","r");  //the text file from
> which I have to extract the string.
>  if(fp1==NULL)
>  {
>   printf("\n File not found");
>   exit(0);
>  }
>  fp2=fopen("12.txt", "w");  // the file into which I
> have to write the extracted string
> 
>  while(!feof(fp1))
>  {
>   ch=fgetc(fp1);   //the loop which extracts the
> character till _ is reached
>   if(ch!='_')
>   {
>    fputc(ch, fp2);
>   }
>   else if(ch!='\n')  //the loop which runs till new
> line is reached, this loop 
>                            doesn't terminate.   
>   {
>    ch=fgetc(fp1);
>   }
>  }
>  printf("\n Successfully completed...");
>  fclose(fp1);
>  //fclose(fp2);
>  getch();
>  return 0;
> }
> 
> 
> Please suggest an improvement on this piece of code
> or debug the logical error in the code.
> 
> The sample of file is as shown......
> pus||hkar_sjs
> pu#|shkar2001_sjs
> 
> I need only the sequence of character upto _..
> Rest of the characters are not be copied into the
> other file.
> 
> 
> 
>               
> ---------------------------------
> Win a BlackBerry device from O2 with Yahoo!. Enter
> now.
> 
> [Non-text portions of this message have been
> removed]
> 
> 

This would be MUCH simpler if done in c++, but here is
a solution in c.



int main()
{
  FILE *fp1, *fp2;
  char ch;
  bool IgnoreRestOfLine = false;
 // clrscr();
  fp1=fopen("11.txt","r") ; //the text file from which
I have to extract the string.

  if (fp1==NULL)
  {
    printf("\n File not found");
    exit(0);
  }

  fp2=fopen("12.txt", "w"); // the file into which I
have to write the extracted string

  while (!feof(fp1))
  {
    ch=fgetc(fp1) ; //the loop which extracts the
character till _ is reached
   
    if (ch == '\n')
    {
      IgnoreRestOfLine = false;  
      fputc('\n', fp2);   // Adds a new line to the
output file 
      continue;
     }  

    if (ch!='_' && !IgnoreRestOfLine)
      fputc(ch, fp2);
    else
     IgnoreRestOfLine = true;
     
  }

  printf("\n Successfully completed... ");

  fclose(fp1);
  fclose(fp2) ;

 // system("PAUSE");
  return(0);
}


Mickey M.
Construction Partner Inc.
http://www.constructionpartner.com


 
____________________________________________________________________________________
TV dinner still cooling? 
Check out "Tonight's Picks" on Yahoo! TV.
http://tv.yahoo.com/

Reply via email to