So I have been programming c++ for a year, but I've never coded in c before until this recent attempt.
Code:
#include <stdlib.h>
#include <stdio.h>
struct Command {
int n;
double start_time;
double duration;
double note;
double amplitude;
};
struct Node{
struct Command* c;
struct Node* next;
};
struct LinkedList{
struct Node* head;
struct Node* tail;
};
void copy(struct Command* origin, struct Command* destination);
void addToList(struct LinkedList* list, struct Node* p);
struct Node* getHighest(struct LinkedList* l);
void removeFromList(struct LinkedList* l, struct Node* n);
void sort(struct LinkedList* unsorted, struct LinkedList* sorted);
int main(int argc, char** argv)
{
struct LinkedList* unsorted = malloc( sizeof(struct LinkedList) );
struct LinkedList* sorted = malloc( sizeof(struct LinkedList) );
struct Node* curr = NULL;
struct Command* temp = malloc( sizeof(struct Command) );
char line[250];
FILE *fr;
fr = fopen ("C:\\Users\\shrikis\\Downloads\\output.sco", "rt");
while(fgets(line, 250, fr) != NULL)
{
if(line[0]=='i')
{
sscanf(line, "%*c %d %lf %lf %lf %lf", &temp->n, &temp->start_time,&temp->duration,&temp->note,&temp->amplitude);
curr = malloc( sizeof(struct Node) );
curr->c = malloc( sizeof(struct Command) );
copy(temp,curr->c);
curr->next = 0;
addToList(unsorted,curr);
}
}
sort(unsorted, sorted);
return 0;
}
void copy(struct Command* origin, struct Command* destination)
{
destination->amplitude = origin->amplitude;
destination->duration = origin->duration;
destination->n = origin->n;
destination->note = origin->note;
destination->start_time = origin->start_time;
}
void sort(struct LinkedList* unsorted, struct LinkedList* sorted)
{
struct Node* highest;
while(unsorted->head!=NULL)
{
highest = getHighest(unsorted);
removeFromList(unsorted,highest);
addToList(sorted,highest);
printf("%lf\n", highest->c->start_time);
}
}
struct Node* getHighest(struct LinkedList* l)
{
struct Node* current_head = l->head;
struct Node* smallest = current_head;
while(current_head!=NULL)
{
if(current_head->c->start_time < smallest->c->start_time)
smallest = current_head;
current_head = current_head->next;
}
return smallest;
}
void removeFromList(struct LinkedList* l, struct Node* n)
{
struct Node* head = l->head;
struct Node* previous = NULL;
while(head!=NULL)
{
if(head==n)
{
if(previous!=NULL)//Incase first node of list (has no previous node)
previous->next = head->next;
else
l->head = head->next;
break;
}
else
{
previous = head;
head = head->next;
}
}
head->next = NULL;
}
void addToList(struct LinkedList* list, struct Node* p)
{
if(list->tail==0)
list->head = list->tail = p;
else
{
list->tail->next = p;
list->tail = p;
}
}
I wrote this program successfully in c++ but I tried to convert it to C with almost no luck at all. The above script is my sad attempt at the conversion. Can anyone offer any suggestions to help me get this program working in C?