This is just a start of my code. I am trying to read a file with a list of names followed by a space and a status, either 1-up or 0-down. So the file would look like this if it had 2 records.
computer1 1
nextcomp 0
So far I could read the file, but when I try to get the string to copy to my list for each line, it crashes on the strcpy function. Im fairly new and this is probably a easy fix, but i just cant figure it out. please help. here is my code
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ALLUP 1
#define NEIGHBORS 2
#define QUIT 3
#define BADRESPONSE -1
#define GOODRESPONSE 4
#define MAXLINE 256
#define MAXNAME 30
#define FILENAME "input.txt"
struct netnode
{
char *computer;
int updown;
struct netnode *prev, *next;
};
typedef struct netnode NETNODE;
void main (void)
{
// Functions
NETNODE *initList (void);
NETNODE *readFileIntoList (void);
void insertNode (char *compName, int status, NETNODE *list);
// Wrapper Functions
void *Malloc(size_t size);
FILE *Fopen(char *file, char *mode);
// Declarations
NETNODE *list;
// Program
list = readFileIntoList();
return;
}
NETNODE* initList (void)
{
NETNODE *list;
list = (NETNODE*)Malloc(sizeof(NETNODE));
list->next = list;
list->prev = list;
list->updown = 0;
return list;
}
NETNODE *readFileIntoList (void)
{
NETNODE *list;
FILE *input;
char line[MAXLINE];
char compName[MAXNAME];
int status;
input = Fopen(FILENAME, "r");
list = initList ();
while (fgets(line, MAXLINE, input))
{
sscanf(line, "%[^ ] %d", &compName, &status);
insertNode(compName, status, list);
}
fclose(input);
return list;
}
void insertNode (char *compName, int status, NETNODE *list)
{
NETNODE *newNode;
newNode = (NETNODE*)Malloc(sizeof(NETNODE));
strcpy (newNode->computer, compName);
newNode->updown = status;
newNode->prev = list->prev;
list->prev->next = newNode;
list->prev = newNode;
newNode->next = list;
list->next = newNode;
return;
}
void *Malloc(size_t size)
{
void *ptr;
if ((ptr = (void *) malloc(size)) == NULL)
{
perror("malloc");
exit(1);
}
return ptr;
}
FILE *Fopen(char *file, char *mode)
{
FILE *fp;
if ((fp = fopen(file, mode)) == NULL)
{
printf("Fopen error on %s!\n", file);
exit(1);
}
return fp;
}
This is just the reading file part so far, I cant get past this part. thanks