Question

Use of fscanf and parsing line by line of a FILE

Asked by: 9703403

I was using fscanf to read in a file and examine each token of this complete file one at a time for the the occurence of a specific keyword.  However I want to read one line from the file. Examine each token in the line and if then when that full line has been examined. I read the next line and examine that until the end of the file.

         char word[MAX_LENGTH];
         FILE *inputfile;

       while( fscanf( inputfile, " %s", word) !=EOF )
        {        
            //Examine word here
         }

The above section of the code basically tokenises the complete file until finished. I want it to do one line and then the next.
Is there a way when using fscanf of knowing when I have reach a newline ?
or should i use scanf ?
Basically I need to know when I have ancountered a newline
Cheers Dave




This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-02-21 at 06:44:42ID21322713
Tags

fscanf

,

line

Topic

C Programming Language

Participating Experts
2
Points
500
Comments
29

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. fscanf() or getc()??
    I have a txt file full of characters(a-zA-Z) and I want to input them into a string so I can manipulate them. should I use fscanf() or getc() --REVISION-- okay some people asked for some clarification on the question, I guess I was being to vague. the exact scenario is: I'm...
  2. fscanf
    fscanf( stream2, "%24c", max_elev); The above instruction reads 24 chars into max_elev. How can i specify a variable number of chars to be read ? Something like int numberofchars=24; fscanf(........ ?????
  3. fscanf problem
    I have this while ( !feof(fp) ) { fscanf(fp, %s, &ptr); printf("%s", ptr); if ( nextchar is \n ) printf("\n"); else printf(" "); } How to check for the next if it is \n or space? I don't wish to use fgetc to ...
  4. fscanf problem
    if this is the file 3 4 5 1 2 3 2 3 4 4 5 4 and i read that while( !feof(fp)) { fscanf(fp, "%d%d%d", &time, &id, &value); ..... } while (q_h != NULL) { printf("%d\n", q_h->time); q_h = q_h->next; } it seems ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: 9703403Posted on 2005-02-21 at 06:45:47ID: 13363062

TYPO: I meant sscanf above not scanf

 

by: KdoPosted on 2005-02-21 at 06:58:22ID: 13363177


The %s format specifier breaks strings at white-spaces (blanks).  You need to use a more robust specifier or an API that reads without parsing, like fgets().

If you use fgets(), you can then use sscanf() or strtok() to parse the string.

Kent

 

by: 9703403Posted on 2005-02-21 at 07:06:30ID: 13363252

If i was to use sscanf, going on example si have looked at. You seem to need to know how many tokens there will be in the input buffer (String) in order to store it somewhere.

Okay -I could use the following:
             ifstream inStream(inputDir, ios::in);
               while (!inStream.eof())
             {
                  inStream.getline(line, 255, '\n');
                         //My Scanf here (or strtok)
                            sscanf( line, " %s", word);
                }
I am not sure how to break the string into clean tokens here though.
All I want is to be able to examine each token now from the line. So %s would be okay but when i do the above it stops after the first token and doesnt read the next. How should that line read.
Cheers

 

by: KdoPosted on 2005-02-21 at 07:10:15ID: 13363294


As I alluded, a more robust (see also, complicated) format specifier will let you read the entire line with fscanf().  (Personally, I much prefer fgets().)

Using your original code:


         char word[MAX_LENGTH];
         FILE *inputfile;

      while( fscanf( inputfile, " %[^\n]", word) !=EOF )
        {        
            //Examine word here
         }

This tells fscanf() to read until newline (\n) is reached.


Kent

 

by: PaulCaswellPosted on 2005-02-21 at 07:33:37ID: 13363507

Dave,

The way I'd do it is to use:
      char terminator;
      while( fscanf( inputfile, "%[^ \n]%c", word, &terminator) !=EOF )

This is a lot like Kents but I am reading up to the first space or newline and collecting whatever caused it to stop. You can then check 'terminator' to see what stopped it. If it's a '\n' then, obviously, you hit a newline.

The main difference between this and what you had will be that multiple spaces will be seen as multiple tokens.

Paul

 

by: 9703403Posted on 2005-02-21 at 07:48:39ID: 13363682

Kent
I used the code you supplied but the fscanf just read the whole file and did not stop at the \n
Also how would the code allow me to read the next line as well and so on.

Paul I will try yours now - thanks . I dont really want the spaces though I just want whole words.
 

 

by: KdoPosted on 2005-02-21 at 07:55:30ID: 13363751


Ahh....  I misunderstood.  Thought that you wanted to read an entire line, processes each word, and then read the next line.

Combining your original code and Paul's suggestion:


         char word[MAX_LENGTH];
         char EndChar;
         FILE *inputfile;

      while( fscanf( inputfile, " %s%c", word, &EndChar) !=EOF )
      {    
         // Examine Word    
         if (EndChar == '\n')
           // End of line after token
       }


Kent

 

by: PaulCaswellPosted on 2005-02-21 at 07:56:12ID: 13363761

Dave,

One more thought! Use "^ \r\n" just to be sure. In this way it will still work if you open the file in binary mode.

With mine, you wont get spaces. Note that there is a space between the '^' and the '\r'. This will ensure you dont get spaces in your token. The fscanf will stop on the first character that IS in the list, i.e. space, cr, lf, and then put the character it DID get into 'terminator'. You can then check 'terminator' to see what it was.

Paul

 

by: 9703403Posted on 2005-02-21 at 08:21:11ID: 13364041

Hi Lads
You are both on the right track. I think I have confused you both a bit though .
Sorry for not being clearer with my explantion.

Based on what I am trying above this is what I want.

[1] Open up a file for reading.
[2a] Read (using fscanf) tokens from the file input stream. (Tokens which are sperated by space)
These tokens can with either a normal text or a '\n'
If the token is a '\n' continue (I only want to be aware that I am on a new line)


I ran the code above but in some cases when I perform the
if (EndChar == '\n')
I get true when it is actually a space
Also for some lines it reads the first or maybe the seconds tokens and ignores the rest of the line
and also it stopped half way through the line and just finished.

Any ideas why
This is the code:

        DIR *dirp;
      FILE *input_file_pointer;
      char inputDir[MAX_LENGTH];
      char word[MAX_LENGTH];      
      char terminator;

            ifstream inStream(inputDir, ios::in);
            input_file_pointer = fopen(inputDir, "r");

             while( fscanf( input_file_pointer, " %s%c", word , &terminator) !=EOF )
            {
                        if(terminator == '\n')
                       printf("New Line \n");
                  else
                     printf("[%s]\n",word);
            }












 

by: PaulCaswellPosted on 2005-02-21 at 08:30:35ID: 13364139

>>Also for some lines it reads the first or maybe the seconds tokens and ignores the rest of the line
This is probably the definition of EOF. Use '> 0' instead of '!= EOF' because fscanf actually returns the number of items read. Note, it maytherefore be worthwhile saving the number of items read because if it was equal to '1' then the terminator character hasnt been read; the end of the file was reached first.

Paul

 

by: KdoPosted on 2005-02-21 at 09:15:09ID: 13364630



           while( fscanf( input_file_pointer, " %s%c", word , &terminator) > 0)
          {
               printf("%s\n",word);          /*  You don't need the braces [] here  */
               if(terminator == '\n')         /*  Also, you should get a value placed in *word*  */
                    printf("New Line \n");   /*  regardless of the value placed into *terminator*  */
          }

 

by: 9703403Posted on 2005-02-21 at 09:18:33ID: 13364657

Hi Lads
Okay Brilliant I am nearly working fully. What you ahve suggested worked
I put in the following code and it works very well. The only small thing that I need is
If there is a blank line in the file. How would I detect it and print it out ?


      while( fscanf( input_file_pointer, " %s%c", word , &terminator) > 0 )
            {
                        if(terminatorFlag  == TRUE)
                        {
                              //reset Flag
                              terminatorFlag  = FALSE;
                              printf("\n");
                        }
                        if(terminator == '\n')
                        {
                              terminatorFlag = TRUE;
                              printf(" ^%s^",word);
                        }
                        else
                        {
                              printf(" [%s]",word);
                         }
         }

 

by: 9703403Posted on 2005-02-21 at 09:19:53ID: 13364665

FYI:

I put in ^^ and [] around the words I was printing just to diffentiate and to debug
So you can ignore those

 

by: PaulCaswellPosted on 2005-02-21 at 09:21:22ID: 13364679

Note that in Kents code above, if the last word does not have a space or a \n at the end, the fscanf will only read 1 field and will leave the terminator as it was. This would only miscalculate your line count if this word was alone on the line but I'd probably make this simple change:

          while( (count = fscanf( input_file_pointer, " %s%c", word , &terminator)) > 0)
 ...
               if(count > 1 && terminator == '\n')         /*  Also, you should get a value placed in *word*  */
...

Paul

 

by: PaulCaswellPosted on 2005-02-21 at 09:24:06ID: 13364698

>>If there is a blank line in the file. How would I detect it and print it out ?
By definition, a blank line is one with no words on it. Count the words!

You will have to decide for yourself whether a line with nothing but spaces on it is 'blank'.

Paul

 

by: 9703403Posted on 2005-02-21 at 09:27:08ID: 13364723

Thats fantastic - You have both been a great help.
Is it Okay if I split the points ?
Thanks a million for your help :-)

 

by: PaulCaswellPosted on 2005-02-21 at 09:31:01ID: 13364755

>>Is it Okay if I split the points ?
NO!!! Give them all to me!!! Kent's got LOADS already!!! ;) ... Just kidding! I wouldnt object to a split. I generally only get upset if I dont get a grade 'A' but even then it doesnt really matter that much.

Paul

 

by: KdoPosted on 2005-02-21 at 09:34:49ID: 13364782


Hi Paul,

As long as he doesn't give them to Sunny, it's a good day.  :)

 

by: 9703403Posted on 2005-02-21 at 09:43:25ID: 13364853

Thanks again Guys.
Just on your last point there Paul
The count always returns 2 as it trys to read a %s and a %c for each scan.
It doesnt appear to read a blank line - Just lines with text on them


 

by: PaulCaswellPosted on 2005-02-22 at 01:12:53ID: 13369885

Dave,

>>The count always returns 2 as it trys to read a %s and a %c for each scan.
What happens if your file just contains one word, no spaces, no returns? I'd bet it returns 1.

>>It doesnt appear to read a blank line - Just lines with text on them
That's because you are using an initial space in " %s%c". This space eats all whitespace characters until a non-whitespace, i.e. blank lines. Using "%[^ \r\n]%c" would act slightly differently, as would "%s%c" (no initial space).

If you are happy with the solution you have then stick with it. Dont worry about the details. Deep knowledge of scanf formats will come with years of use.

Paul

 

by: 9703403Posted on 2005-02-23 at 07:01:59ID: 13382898

Hey Paul
I noticed a small problem but an imprtant one for me.
I can submit this as a new question if youd like as I know you have spent enough time alread on it.
The question is that it misses the very last token in the file
So for example if there was closing brace on the last file as follows

//
} <- it does not read this one

while( (fscanf( inStream, " %s%c", word , &terminator)) !=EOF )
{
//Do Stuff here
}

Dave

 

by: 9703403Posted on 2005-02-23 at 07:04:01ID: 13382918

It is reading the } as a terminating character

 

by: KdoPosted on 2005-02-23 at 07:10:00ID: 13382983


Hi Dave,

If you check, you'll probably find that a lot of other characters are also getting treated as a terminating character OR combined into a concatenated string.  Exact syntax and spacing is an issue here.

"abcd efgh" and "abcdefgh" are clearly different strings.
"abcd 1111" and "abcd1111" are also different.

"while (" and "while(" are too.

The solution is a really creative format string, or to parse the data yourself.

Kent

 

by: PaulCaswellPosted on 2005-02-23 at 07:22:51ID: 13383118

By all means parse the data yourself but "%[^ \r\n]%c" IS taking more control. It's specifying exactly what is not allowed in your token.

Paul

 

by: 9703403Posted on 2005-02-23 at 07:42:00ID: 13383347

Hey thanks again
I discovered a problem with it which I should be able to mess around with. I was
checking %s%c however this was checking the character just after the %s but the '\n' was occuring a few places on and not immediately following the %s.



 

by: KdoPosted on 2005-02-23 at 07:54:41ID: 13383500


Hi Dave,

It looks like you're trying to parse C source code.  Or perhaps other text that is quite C like.

scanf() poses challenges here that are tricky to overcome.

--  'A' is really a single token.
--  "This is really a single token, too"
--  "As is this, even when you \"quote\" embedded text"
--  X0 is a valid C identifier,
--  0X is not.
--  0f isn't either, but it IS a valid constant

etc....

 

by: 9703403Posted on 2005-02-23 at 08:03:04ID: 13383611

Yeah I am reading in Java files. Examing each line and then ouputting the line to a new file in a different directory.
Hence I need to know when I have encountered the end of a line.
So I read each word of the java file and when I encounter certain key words I may do something to it and then I output to file.

I nearly have it working perfect until I discovered one or two files didnt compile afterwards.
This was because for example I had to lines as follows:

        // 1 corresponds to second field on summary screen, face value  \n  <- new line char here
        treePane.setTransferInfo(voucherOrderTable.getValueAt

When I parsed the lines and outputted (unchanged) to file. it came out like all in one line which causes a compile error. For obvious reasons the fscanf loop failed to detect the \n at the end of the first line as it was two spaces on from the end of the line and
my parser was looking for '%s%c' instead of  '%s   %c'

How would I sort this out once and for all
Cheers Dave

I put the \n in abovefor demonstration purposes








 

by: 9703403Posted on 2005-02-23 at 08:06:21ID: 13383658

See above comment as well :

Paul this code:
while( (fscanf( inStream, "%[^ \r\n]%c", word , &terminator)) !=EOF )
{
}
Reads the tokens until the first \n but then just loops on the last word. How do I get it to go to the next line and continue on ?
I think it must be staring me in the face but I its not clicking
Sorry
                   
                   

 

by: KdoPosted on 2005-02-23 at 08:24:46ID: 13383875


Some tokens are really multi-character tokens.

a *=  b;

For parsing, you don't care if the operator '*=' is treated a one or two tokens.

a *= b;
a*=b;
a * = b ;

are all valid and should produce the same result.


a  *=  /*  compute residual  */  b;

But in the line above, '/*' and '*/' clear DO get treated as a single entity.

Similarly, you don't really want to parse anything past '//', instead you want to copy the rest of the line.  (This appears to have bitten you in your example above.)

I tend to parse this kind of text myself.  The code gets a bit long, but to me, it's easier than grabbing generic text from the source file and trying to keep track of all of the possible embedded statuses.

Having processed:

a =
a *=

You have the same status, but the second line has an embedded status because of the pending multiplication.  A parser will simply put this on the stack, but your process doesn't sound recursive and doesn't seem to utilize a stack.

In general, I have a generic function called get_token().  With each call it checks to see if there is any data in the "line buffer" and if not it reads a line from the source file  If there is data in the line buffer, it continues with the current text.  I then grab the first character and build my token based on the character.

  while (1)
  {
    if (LineEmpty)
    {
      fgets (LineBuffer, LINE_LENGTH, stdin);
      if (feof (stdin))
        break;
      ptr = LineBuffer;
    }
    while (*ptr == ' ' || *ptr == '\t')  // skip space and tab chars
      *ptr++;
    if (*ptr == '\n')
      continue;
    end = ptr;
    switch (*ptr)
    {
      case '(':
      case '{':
      case '[':
         // etc.  Handle single character tokens
         break;
      case '=':  // check to see if '=' or '==' token
         break;
      case '-':
      case '*:
      case '+'  // check for +, +=, -, -=, *, *=
         break;
      case '/':  // check for /, /=, /*, //
         break;
      case '#'  // check for #include, #define, #if, #pragma, etc
         break;
      case '"':  // extract string
         break;
      case '/'':  // extract quoted single character
         break;
      default:
         if (isapha (*ptr))
           // handle alpha data
         else if (isdigit (*ptr))
           // handle numeric data
         else
           // error...


Of course, this may be overkill for what you're trying to do....

Kent

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...