-2

For a project, I need to take an adjacency matrix as input in a C program from a text file. The text file contains the edge details of the graph for which the matrix is to be constructed. The format of the text file is given below.

   5    4
   3    2
   0    1
   1    0
   4    5

Each line contains an edge, shown by tab-separated values. For example, in the first line, there is an edge from node 5 to node 4. I need to take input from this file and show the matrix as output in C. Can anyone please help me how to proceed?

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
amun101
  • 1
  • 1
  • 1

1 Answers1

2
  1. Open file in read mode.

  2. Declare an 2-D array namely adj[][](size according to question be adj[6][6]).

  3. Initialize all elements of array to 0.

  4. Read file and store value it into two variables n and m (using for example the fscanf() function).

  5. Update value in adj[][] to 1 corresponding to index n and m.

(Steps 4 and 5 inside a loop to read file until EOF)

  1. Then close file.
Laogeodritt
  • 750
  • 4
  • 15
ameyCU
  • 16,489
  • 2
  • 26
  • 41
  • I am relatively new to file handling. So I cant figure out how to read the tab-separated values into variables in each line. I mean, which function do I have to use? – amun101 Jul 11 '15 at 17:52
  • Look into `fscanf` in `stdio.h`. It lets you specify a format of expected data to read from a file, and the variables to read the data into. – Laogeodritt Jul 11 '15 at 17:59
  • @amun101 You can learn about `fscanf` from here -http://www.tutorialspoint.com/c_standard_library/c_function_fscanf.htm – ameyCU Jul 11 '15 at 18:01
  • for ( x = 0;x < v;x++ ) { for ( y = 0;y < v;y++ ) adj[x][y]=0; } while(!eof(fp)) { fscanf(fp, " %d %d ", &origin, &destin); adj[origin][destin]=1; } fclose(fp); for ( x = 0;x < v;x++ ) { for ( y = 0;y < v;y++ ) printf("%d", adj[x][y]); printf("\n"); } – amun101 Jul 11 '15 at 19:13
  • this is what i have done after steps 1 & 2. is this correct? @Laogeodritt – amun101 Jul 11 '15 at 19:14
  • okay it is solved now. i had given eof instead of feof, so it was not working. it's working fine now. thanks – amun101 Jul 11 '15 at 19:47
  • @ EOF I just meant here as end of file . Well you resolved it by feof nice work . – ameyCU Jul 12 '15 at 05:35