How do I read a file line by line and also read each integer

How do I read a file line by line and also read each integer in C? Here are the details:

You will read your input graph from an input file named graphin.txt of the following adjacency list representation where each xij is the j\'th neighbor of vertex i (vertex labels are 1 through n) and wij is the weight of the edge between vertices i and Xij:

1: x11 w11 x12 w12 x13 w13...
2: x21 w21 x22 w22 x23 x23 ...
.
.
n: xn1 wn1 xn2 wn2 xn3 wn3 ...

Here is what my input file looks like:

1: 2 8 3 5
2: 1 8 3 4 4 6 5 3
3: 1 5 2 4 5 2
4: 2 6 5 5 6 1
5: 2 3 3 2 4 5 6 4
6: 4 1 5 4

So for the first line it should read it as the first edge has a source vertice of 1, a destination vertice of 2, and a weight of 8, the second edge has a source vertice of 1, a destination vertice of 3, and a weight of 5. Then it would go to the next line and read the first edge in that line, making the third edge have a source vertice of 2, a destination of 1, and a weight of 8, and so on and so forth.

Solution

#include<stdio.h>
int main(){
   char filename[] = \"graphin.txt\";
   FILE *file = fopen(filename,\"r\");
   int i=0;
   if(file != NULL){
       char line[5000]; //line will not contain more than these number of characters
       while(fgets(line,sizeof line,file) != NULL){ // fgets will read the file specified line by line
           i = 0;
           while(line[i] != NULL){
               if(line[i] >= 48){ //Inorder to skip the spaces
                   printf(\"%c \",line[i]); //line[i] holds ASCII number of the number you wanted , you can use it whatever way you want by converting it into integer using following ways
// This will contain ASCII value of the number, inorder to get the real number we can decrease the value with 48 because it is the ASCII value of zero
// Or else if we just want to print it , we can specify as %c in printf arguments.
               }
               i++;
           }
           printf(\"\ \");
       }
       fclose(file);
   }
   else{
       perror(filename);
   }
   return 1;
}

How do I read a file line by line and also read each integer in C? Here are the details: You will read your input graph from an input file named graphin.txt of

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site