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

Scanning whole lines and then checking contents

Status
Not open for further replies.

graemephillips

Programmer
Mar 8, 2004
8
0
0
GB
Could someone tell me how to open a program, scan through whole lines in C, check for certain parameters and then assign values to variables in C? For instance, I have to use the C program to open a program named cube.tri, whose format is shown below: -

8 6
1 1 1
1 1 -1
1 -1 1
1 -1 -1
-1 1 1
-1 1 -1
-1 -1 1
-1 -1 -1
4 0 1 3 2
4 4 6 7 5
4 0 2 6 4
4 1 5 7 3
4 0 4 5 1
4 2 3 7 6

The section of code is a description of a cube. The first line gives the number of vertices followed by the number of faces on the shape. Next is a list of the vertices, according to the number stated in the first line, each with 3 co-ordinates. Once all the vertices have been stated, there are the face descriptions. The first number in the line states how many vertices are used to make up the corners of the faces. The following numbers refer to the vertices, whose co-ordinates will be used in the construction of the face, which are stated in chronological order in the vertices part of the file; for instance, 1 would be the (1, 1, 1) vertex and 2 the (1, 1, -1) vertex etc.
 
No, I finished school back in 2001. I am mostly ok on the program, but there are unfortunately some gaps in my knowledge.
 
I'd say something like this might serve as a starting base.
Code:
#include <stdio.h>

int main(void)
{
   static const char filename[] = "file.txt";
   FILE *file = fopen(filename, "r");
   if ( file != NULL )
   {
      char line[128];
      if ( fgets(line, sizeof line, file) != NULL )
      {
         int vertices, faces;
         if ( sscanf(line, "%d %d", &vertices, &faces) != 2 )
         {
            puts("error 1");
            goto end;
         }
         printf("vertices = %d, faces = %d\n", vertices, faces);
         /*
          * Likely you'd prefer to dynamically allocate vertex and face
          * structures here and loop through the file data.
          */
      }
end:  fclose(file);
   }
   else
   {
      perror(filename);
   }
   return 0;
}
It ought to be enough to jog you memory at least.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top