C Graph

How to write a C Program - C Graph in C Programming Language ?


Solution For C Graph:

#include<stdio.h>
#include<stdlib.h>

//file name
char str[] = "sample.col\0";

//declare enum without specific name
enum {
G_PROPERTY = 'p',
G_EDGE = 'e',
BUF_SIZE = 64
};

struct node {
unsigned id;
struct node *next;
};

struct graph {
unsigned nOfNodes;
unsigned nOfEdges;

struct {
unsigned length;
        struct node *first;
        struct node *last;
} *nodes;

int (*add_edge)(struct graph*, unsigned, unsigned);

//gr->addEdge()
};

//allocate memory for graph and initialize graph
struct graph *init_graph (void);

//add edge to grap

//add edge to graphh
int graph_add_egde (struct graph *g, unsigned from, unsigned to);

//parse graph
int parse_graph (FILE *file, struct graph *g);

//parse property file, called from parse_graph()
int parse_property_line (char line[]);

//parse edge, called from parse_graph()
int parse_edge (char line[], struct graph *g);

//verbose
int verbose = 0;

int main (void) {
//open file
FILE *file = fopen("sample.col", "r");

//declare and assign variable for graph
struct graph *g = init_graph();

//parse graph
parse_graph(file, g);

//close file
fclose(file);

//return 0
return 0;
}

int parse_graph (FILE *file, struct graph *g) {
//check if file parameter is null
if (file == NULL) {
return 1;
}

//declare and assign variable for line
char line[BUF_SIZE] = {};

while (fgets(line, (sizeof line) / sizeof(char), file) != NULL) {
switch (line[0]) {
case G_PROPERTY:
parse_property_line(line);
break;
case G_EDGE:
parse_edge(line, g);
break;
default:
if (verbose == 1) {
printf("[DEBUG] failure in line: %s", line);
}

break;
}
}

//return 0
return 0;
}

int parse_property_line (char line[]) {
//delcare and assign variable for number of nodes
unsigned nOfNodes = 0;
unsigned nOfEdges = 0;

//scan readed line and check, if line format is correct
if (sscanf(line, "p edge %u %u", &nOfNodes, &nOfEdges) < 2) {
return 1;
}

//print number of nodes to console
printf("Number of nodes: %u\nNumber of edges: %u\n", nOfNodes, nOfEdges);

return 0;
}

int parse_edge (char line[], struct graph *g) {
//declare variables for from and to nodes
unsigned from = 0;
unsigned to = 0;

//scan readed line and check, if line format is correct
if (sscanf(line, "e %u %u", &from, &to) < 2) {
return 1;
}

printf("Edge from %u to %u\n", from, to);

return 0;
}

struct graph *init_graph (void) {
struct graph *g = malloc(sizeof *g);

//check, if malloc was successful
if (g == NULL) {
//error function from stdio.h, prints error message to console
perror("init_graph");

//exit with error code
exit(EXIT_FAILURE);
}

//set number of nodes and edges to 0, because graph doesnt have nodes and edges yet
g->nOfNodes = 0;
g->nOfEdges = 0;

//clear node list
g->nodes = NULL;

//return graph struct
return g;
}

int graph_add_edge (struct graph *g, unsigned from, unsigned to) {
//
}


Learn More :