Program sorts the data in the wrong way - c

I have to wirte a project for school, here is Program description
As can you see in the program description i have to sort the books by labels. Right now for some reason books that do not belong to specific label are printed under that label. For exemple Plato is printed under medival
I cannot find where did I made a mistake, I will be grateful for any help.
Here is my code:
#define _CRT_SECURE_NO_WARNINGS
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#include <stdio.h>
#include <string.h>
typedef struct BOOK Book;
struct BOOK
{
char *author;
char *title;
Book *next;
};
typedef struct LABEL Label;
struct LABEL
{
char *text;
Label *next;
Book *books;
};
void clear(Label** head);
void addLabel(Label **head, Label *elem);
void addBook(Book **head, Book **elem);
void readFromFile(char *fileName, char *outputFileName, Label *Ihead);
void saveBooks(FILE *file, Book *head);
void saveLabels(FILE *file, Label *Ihead);
void saveToFile(char *fileName, Label *Ihead);
void ComandConsole(int argc, char* argv[], int* fileinput, int* fileoutput);
Label* checkIfExists(Label **head, char *labelText);
Label* checkIfExists(Label **head, char *labelText)
{
Label *tmp = *head;
while (tmp != NULL)
{
if (strcmp(labelText, tmp->text) == 0)
return tmp;
tmp = tmp->next;
}
return NULL;
}
void addLabel(Label **head, Label *elem)
{
Label *temp = NULL;
if ((temp = checkIfExists(head, elem->text)) == NULL)
{
if (*head == NULL)
{
*head = elem;
return;
}
temp = *head;
while (temp->next != NULL)
temp = temp->next;
temp->next = elem;
}
else
addBook(&(temp->books), &(elem->books));
}
void addBook(Book **head, Book **elem)
{
Book *pom = *head;
if (strcmp(pom->author, (*elem)->author) > 0)
{
(*elem)->next = (*head)->next;
*head = *elem;
*elem = pom;
(*head)->next = *elem;
return;
}
while (pom->next != NULL && (strcmp((*elem)->author, pom->author) > 0))
pom = pom->next;
(*elem)->next = pom->next;
pom->next = *elem;
}
void readFromFile(char *fileName, char *outputFileName, Label *head)
{
FILE* input;
if ((input = fopen(fileName, "r")) == NULL)
{
printf("Reading failed!\n");
exit(1);
}
char buf[255];
while (fgets(buf, sizeof buf, input) != NULL)
{
Book *ksiazka = (Book*)malloc(sizeof(Book));
ksiazka->next = NULL;
char *store = strtok(buf, ";");
char * autor = (char*)malloc(sizeof(char)*strlen(store) + 1);
strcpy(autor, store);
ksiazka->author = autor;
store = strtok(NULL, ";");
char * tytul = (char*)malloc(sizeof(char)*strlen(store) + 1);
strcpy(tytul, store);
ksiazka->title = tytul;
store = strtok(NULL, "\n");
char * label = (char*)malloc(sizeof(char)*strlen(store) + 1);
strcpy(label, store);
char *tmp = strtok(label, ",\n");
while (tmp != NULL)
{
Label *newLabel = (Label*)malloc(sizeof(Label));
newLabel->books = NULL;
newLabel->next = NULL;
char *labelText = (char*)malloc(sizeof(char)*strlen(tmp) + 1);
strcpy(labelText, tmp);
newLabel->text = labelText;
newLabel->books = ksiazka;
addLabel(&head, newLabel);
tmp = strtok(NULL, ",\n");
}
}
saveToFile(outputFileName, head);
fclose(input);
}
void clear(Label** head)
{
while (*head != NULL)
{
Label* cur = *head;
*head = (*head)->next;
Book* a = cur->books;
while (a != NULL)
{
Book* b = a;
a = a->next;
free(b->author);
free(b->title);
free(b);
}
free(cur->text);
free(cur);
}
}
void saveBooks(FILE *file, Book *head)
{
Book *tmp = head;
while (tmp != NULL)
{
fprintf(file, "%s, %s\n", tmp->author, tmp->title);
tmp = tmp->next;
}
fprintf(file, "\n");
}
void saveLabels(FILE *file, Label *head)
{
Label *tmp = head;
while (tmp != NULL)
{
fprintf(file, "%s:\n", tmp->text);
if (tmp->books != NULL)
{
saveBooks(file, tmp->books);
}
tmp = tmp->next;
}
}
void saveToFile(char *fileName, Label *head)
{
FILE *output;
if ((output = fopen(fileName, "w")) == NULL)
{
printf("Writing failed!\n");
exit(1);
//clear(&head);
}
else
{
saveLabels(output, head);
}
//clear(&head);
fclose(output);
}
void ComandConsole(int argc, char* argv[], int* fileinput, int* fileoutput)
{
int i;
for (i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
switch (argv[i][1])
{
case 'i':
{
i++;
if (i == argc) break;
*fileinput = i;
}
break;
case 'o':
{
i++;
if (i == argc) break;
*fileoutput = i;
}
break;
default:
{
printf("Wrong parameter");
} break;
}
}
}
int main(int argc, char* argv[])
{
int fileinputname = 0;
int fileoutputname = 0;
ComandConsole(argc, argv, &fileinputname, &fileoutputname);
if (fileinputname == 0 || fileoutputname == 0)
{
printf("Wrong parrametes");
getchar();
return 1;
}
Label *head = NULL;
readFromFile(argv[fileinputname], argv[fileoutputname], head);
_CrtDumpMemoryLeaks();
return 0;
}

Related

Variable value changing after returning to the loop

I've been coding for a C - Binary Search Tree, but the Program always change variable when returning to the loop. I've tried debugging it and checked every pointer but found no errors.
There is a simple run(bold for input, italic for notes)
a
Please enter name of pet:
aaa //pet name, input
Please enter pet kind:
bbb //pet kind, input
add pet success
aaa //pet name, is correct
//pet kind, return to 0
q
0b //pet name, turn to 0b
//pet kind, always 0
Bye.
The code is the next:
main.c
#include "tree.h"
#define CHECK
char menu(void);
void addpet(Tree *pt);
char *s_gets(char *st, int n);
int main(void)
{
Tree pets;
char choice;
InitializeTree(&pets);
while ((choice = menu()) != 'q')
{
switch (choice)
{
case 'a':
addpet(&pets);
#ifdef CHECK
printf("%s", pets.root->head->petname);
printf("%s", pets.root->head->petkind); // petkind back to 0
#endif
break;
default:
puts("Switching error");
}
}
#ifdef CHECK
puts(pets.root->head->petname); // trun to '\000' '372' '\333' 'b' '\376' '\177'
puts(pets.root->head->petkind); // always 0
#endif
puts("Bye.");
return 0;
}
char menu(void)
{
int ch;
ch = getchar();
while (getchar() != '\n')
continue;
return ch;
}
void addpet(Tree *pt)
{
Item temp;
if (TreeIsFull(pt))
puts("No room in the club!");
else
{
puts("Please enter name of pet:");
s_gets(temp.petname, SLEN);
puts("Please enter pet kind:");
s_gets(temp.petkind, SLEN);
temp.next = NULL;
if (AddItem(&temp, pt))
puts("add pet success");
}
}
char *s_gets(char *st, int n)
{
char *ret_val;
char *find;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n');
if (find)
*find = '\0';
else
while (getchar() != '\n')
continue;
}
return ret_val;
}
tree.c
#include "tree.h"
static Node *MakeNode(Item *pi);
static bool ToLeftNode(const Node *i1, const Node *i2);
static bool ToRightNode(const Node *i1, const Node *i2);
static void AddNode(Node *new_node, Node *root);
static PairNode SeekNode(const Node *pn, const Tree *ptree);
static PairItem SeekList(Node *, const Item *);
void InitializeTree(Tree *ptree)
{
ptree->root = NULL;
ptree->size = 0;
}
bool TreeIsFull(const Tree *ptree)
{
if (ptree->size == MAXITEMS)
return true;
else
return false;
}
bool AddItem(Item *pi, Tree *ptree)
{
Node *new_node;
PairNode seek_node;
PairItem seek_list;
if (TreeIsFull(ptree))
{
fprintf(stderr, "Tree is full\n");
return false;
}
new_node = MakeNode(pi);
if (new_node == NULL)
{
fprintf(stderr, "Couldn't create node\n");
return false;
}
if ((seek_node = SeekNode(new_node, ptree)).child != NULL)
{
if ((seek_list = SeekList(seek_node.child, pi)).child != NULL)
{
fprintf(stderr, "Attempted to add duplicate item\n");
return false;
}
seek_list.child = pi;
ptree->size++;
return true;
}
ptree->size++;
if (ptree->root == NULL)
ptree->root = new_node;
else
AddNode(new_node, ptree->root);
return true;
}
static void AddNode(Node *new_node, Node *root)
{
if (ToLeftNode(new_node, root))
{
if (root->left == NULL)
root->left = new_node;
else
AddNode(new_node, root->left);
}
else if (ToRightNode(new_node, root))
{
if (root->right == NULL)
root->right = new_node;
else
AddNode(new_node, root->right);
}
else
{
fprintf(stderr, "location error in AddNode()\n");
exit(1);
}
}
static bool ToLeftNode(const Node *i1, const Node *i2)
{
if (strcmp(i1->petname, i2->petname) < 0)
return true;
else
return false;
}
static bool ToRightNode(const Node *i1, const Node *i2)
{
if (strcmp(i1->petname, i2->petname) > 0)
return true;
else
return false;
}
static Node *MakeNode(Item *pi)
{
Node *new_node;
new_node = (Node *)malloc(sizeof(Node));
if (new_node != NULL)
{
strcpy(new_node->petname, pi->petname);
new_node->head = pi;
new_node->left = NULL;
new_node->right = NULL;
}
return new_node;
}
static PairNode SeekNode(const Node *pn, const Tree *ptree)
{
PairNode look;
look.parent = NULL;
look.child = ptree->root;
if (look.child == NULL)
return look;
while (look.child != NULL)
{
if (ToLeftNode(pn, look.child))
{
look.parent = look.child;
look.child = look.child->left;
}
else if (ToRightNode(pn, look.child))
{
look.parent = look.child;
look.child = look.child->right;
}
else
break;
}
return look;
}
static PairItem SeekList(Node *pn, const Item *pi)
{
PairItem seek;
seek.child = pn->head;
seek.parent = NULL;
while (seek.child != NULL)
{
if (strcmp(seek.child->petname, pi->petname) == 0 &&
strcmp(seek.child->petkind, pi->petkind) == 0)
break;
seek.parent = seek.child;
seek.child = seek.child->next;
}
return seek;
}
tree.h
#ifndef TREE_H_
#define TREE_H_
#define SLEN 20
#define MAXITEMS 10
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct item{ char petname[SLEN]; char petkind[SLEN]; struct item *next;} Item;
typedef struct node{ char petname[SLEN]; Item *head; struct node *left; struct node *right;} Node;
typedef struct tree{ Node *root; int size;} Tree;
typedef struct pairnode{ Node *parent; Node *child;} PairNode;
typedef struct pairitem{ Item *parent; Item *child;} PairItem;
void InitializeTree(Tree *ptree);
bool AddItem(Item *pi, Tree *ptree);
#endif
My question was answered elsewhere.
Modify function addpet:
void addpet(Tree* pt)
{
Item* temp = (Item*)malloc(sizeof(Item));
puts("Please enter name of pet:");
s_gets(temp->petname, SLEN);
puts("Please enter pet kind:");
s_gets(temp->petkind, SLEN);
temp->next = NULL;
if (AddItem(temp, pt))
puts("add pet success");
}

rename() function differs in levels of indirection from int

I'm trying to write a code that uses linked lists and files, to maintain actions (functions) that are given on a text file, instead of receiving them from the user.
For some reason i'm encountering an error which says:
"Severity Code Description Project File Line Suppression State
Error C2040 'rename': 'hw_component *(char *,char *,hw_component *)' differs in levels of indirection from 'int (const char *,const char *)' EX5_313410961 c:\users\edave\source\repos\ex5_313410961\ex5_313410961\shahar_connection.c 172"
I'm having trouble understanding if the problem is the actual function rename() or because of the actions() function.
The code is very long so ill post the relevant section only.
#define _CRT_SECURE_NO_WARNINGS
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define NAME_LENGTH 200
typedef struct hw_component
{
char name[NAME_LENGTH];
int copies;
struct hw_component *next;
}hw_component;
hw_component *create_component(char* name,int copies)
{
if (name != NULL && strlen(name) > NAME_LENGTH)
return NULL;
hw_component *comp = (hw_component*)malloc(sizeof(hw_component));
if (comp == NULL)
{
printf("Error: memory allocation failed\n");
return NULL;
}
strcpy(comp->name, name);
comp->copies = copies;
comp->next = NULL;
return comp;
}
hw_component *add_sort(hw_component* head, int copies, char *name)
{
hw_component *iter, *prev = NULL;
hw_component *new_comp = create_component(name, copies);
if (head == NULL)
return new_comp;
if (strcmp(new_comp->name, head->name) < 0)
{
new_comp->next = head;
return new_comp;
}
iter = head;
while (iter != NULL && strcmp(iter->name, new_comp->name) < 0)
{
prev = iter;
iter = iter->next;
}
prev->next = new_comp;
new_comp->next = iter;
return head;
}
hw_component *initialize(char *argv[])
{
hw_component *list_of_comp = NULL;
FILE *fp = NULL;
char dolar[2] = "$";
fp = fopen(argv[1],"r");
if (fp == NULL)
{
printf("Error: opening %s failed\n", argv[1]);
exit(1);
}
while (!feof(fp))
{
char str[400], *token, *str_num;
fgets(str, 400, fp);
int numb;
token = strtok(str,dolar);
str_num = strtok(NULL, dolar);
numb = atoi(str_num);
list_of_comp=add_sort(list_of_comp, numb, token);
}
fclose(fp);
return list_of_comp;
}
void finalize(hw_component *head, char *argv[])
{
hw_component *temp;
FILE *fp = NULL;
int temp_num;
char *str,*num_str;
fp = fopen(argv[3], "w");
if (fp==NULL)
{
printf("Error: opening %s failed\n", argv[3]);
while (head!=NULL)
{
temp = head;
head = head->next;
free(temp);
}
}
while (head!=NULL)
{
temp = head;
fprintf(fp,"%s $$$ %d\n",temp->name,temp->copies);
head = temp->next;
free(temp);
}
fclose(fp);
}
hw_component *remove_comp_by_name(hw_component *head_comp, char comp_name[NAME_LENGTH + 1])
{
hw_component *temp_ptr = head_comp;
hw_component *prev_ptr;
hw_component *zero_copies_check = head_comp;
if (head_comp == NULL)
{
return head_comp;
}
if (strcmp(temp_ptr->name, comp_name) == 0)
{
head_comp = head_comp->next;
free(temp_ptr);
return head_comp;
}
while (temp_ptr != NULL && strcmp(temp_ptr->name, comp_name) != 0)
{
prev_ptr = temp_ptr;
temp_ptr = temp_ptr->next;
}
if (temp_ptr != NULL)
{
prev_ptr->next = temp_ptr->next;
free(temp_ptr);
}
while (zero_copies_check != NULL)
{
if (zero_copies_check->copies == 0)
{
free(zero_copies_check);
}
zero_copies_check = zero_copies_check->next;
}
return head_comp;
}
hw_component *rename(char old_name[NAME_LENGTH], char new_name[NAME_LENGTH], hw_component *head_comp)
{
hw_component *temp_comp = head_comp;
int num_of_copies = 0;
if (head_comp == NULL)
{
return head_comp;
}
while (temp_comp != NULL && strcmp(temp_comp->name, old_name) != 0)
{
temp_comp = temp_comp->next;
}
num_of_copies = temp_comp->copies;
head_comp=remove_comp_by_name(head_comp, old_name);
head_comp=add_sort(head_comp, num_of_copies, new_name);
return head_comp;
}
hw_component *return_comp(hw_component *head, char name_of_comp[], int copies)
{
hw_component *temp_comp = head;
if (head == NULL)
{
return head;
}
while (temp_comp != NULL && strcmp(temp_comp->name, name_of_comp) != 0)
{
temp_comp = temp_comp->next;
}
if (temp_comp != NULL)
{
temp_comp->copies += copies;
}
else
{
add_sort(head, name_of_comp, copies);
}
return head;
}
int choose_act(char *str)
{
char init[12] = "Initialize ", rename[8]="Rename ",fire[6]="Fire ";
char retu[24] = "Returned_from_customer ", prod[12]="Production " ,fatal[19]="Fatal_malfunction ";
char finalize[] = "Finalize";
if (strcmp(str,init)==0)
return 1;
if (strcmp(str, rename)==0)
return 2;
if (strcmp(str, retu)==0 || strcmp(str, prod)==0)
return 3;
if (strcmp(str, fire)==0 || strcmp(str, fatal)==0)
return 4;
if (strcmp(str, finalize)==0)
return 5;
}
void actions(char *argv[])
{
char dolar[2] = "$";
hw_component *head;
FILE *fp = NULL;
char str[400], *token, *name, *old_name;
int choise = 0, numb;
fp = fopen(argv[2], "r");
if (fp == NULL)
{
printf("Error: opening %s failed\n", argv[2]);
exit(1);
}
while (!feof(fp))
{
fgets(str, 400, fp);
token = strtok(str,dolar);
choise = choose_act(token);
head = initialize(argv);
switch (choise)
{
case 1:
break;
case 2:
old_name = strtok(str, dolar);
name = strtok(str, dolar);
printf("%s %s", old_name, name);
head=rename(old_name,name,head);
break;
case 3:
name = strtok(str, dolar);
numb = atoi(strtok(str, dolar));
head=return_comp(head, name, numb);
break;
case 4:
name = strtok(str, dolar);
numb = atoi(strtok(str, dolar));
head=fatal_maf(head, name, numb);
break;
case 5:
finalize(head,argv);
break;
default:
break;
}
}
}
int check_argc(int argc)
{
int numb = argc;
if (argc != 3)
{
printf("Error: invalid number of arguments (<%d> instead of 3)\n", numb);
return 0;
}
return 1;
}
int main(int argc, char *argv[])
{
int res = 0;
res=check_argc(argc);
if (res == 1)
actions(argv);
return 0;
}
You library already defines a function called rename(), which is prototyped in and included by adding stdio.h, which is creating the conflict with your user-defined function.
As per the lined manual, the signature of the library-defined rename() is int rename (const char *, const char*), whereas as er your function definition, you have a signature as hw_component *rename(char *, char *, hw_component *) - which does not match and your compiler is showing you correct warning (and error) message.
Solution: Use a different name for your function.
You cannot name your custom function rename while including stdio.h, because the name collides with the standard library function rename. Name your own function something different.
The standard function is
int rename(const char *old, const char *new);
So it has type int (const char *, const char *), the same type that the compiler is complaining about a conflict with.

pointer called by reference doesnt work

Hi i have a problem with the next code which i had posted before here, but yesterday i was working on my computer and all of the sudden the screen froze and when i restarted it my code was gone!! it was erased, so i had to start over. The code had to search a codop in a linked list, but it doesnt work, i keep getting the message "CODOP NOT FOUND", i thought that the problem was in the calling of pointers as pass by value, so i called it by reference but it doesnt work either, if someone could tell me how to solve it i would apreciate it a lot
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
char *instruction;
struct node *next;
}COD;
void printList(COD *head);
void SearchEndLine(FILE *hc12);
void listTABOP(COD **head);
COD *lastElement(COD **head);
COD *createNode(char *ins);
void insertEnd(char *ins,COD *last);
char *Operands_Table(FILE *hc12);
COD *searchCodop(COD *head,char *codop);
void Remove(char *c);
int main()
{
COD *head = NULL,*found = NULL;
char *codop = "BLE";
listTABOP(&head);
printList(head);
if((found = searchCodop(head,codop)) == NULL)
{
printf("CODOP NOT FOUND\n");
printf("%s\n",codop);
}
return 0;
}
void SearchEndLine(FILE *hc12)
{
int car;
while((car = fgetc(hc12))!= '\n')
;
}
void Remove(char *c)
{
char *ptr;
if(((ptr = strchr(c,'\n'))!= NULL)||((ptr = strchr(c,'\t'))!= NULL)||((ptr = strchr(c,' '))!= NULL))
*ptr = '\0';
}
void listTABOP(COD **head)
{
int car;
FILE *hc12;
COD *last = NULL;
char *ins;
if((hc12 = fopen("Tabla_OP.txt","r"))!= NULL)
{
while((car = fgetc(hc12))!= EOF)
{
if(car != '\t')
{
ins = Operands_Table(hc12);
if(*head == NULL)
*head = createNode(ins);
else
{
last = lastElement(head);
insertEnd(ins,last);
}
}
else
SearchEndLine(hc12);
}
}
else
printf("No se pudo abrir el archivo");
}
COD *lastElement(COD **head)
{
COD *ptr;
ptr = *head;
while(ptr->next != NULL)
ptr = ptr->next;
return ptr;
}
char *Operands_Table(FILE *hc12)
{
int car,lon = 0,pos;
char *c;
fseek(hc12,-1,SEEK_CUR);
pos = ftell(hc12);
do
{
car = fgetc(hc12);
lon++;
}while(car != '\t');
fseek(hc12,pos,SEEK_SET);
c = (char*)calloc((lon+1),sizeof(char));
fgets(c,lon+1,hc12);
Remove(c);
SearchEndLine(hc12);
return c;
}
COD *searchCodop(COD *head,char *codop)
{
COD *ptr;
for(ptr = head;ptr != NULL;ptr = ptr->next)
{
if(ptr->instruction == codop)
return ptr;
}
return NULL;
}
void insertEnd(char *ins,COD *last)
{
last->next = createNode(ins);
last->next->next = NULL;
last = last->next;
}
COD *createNode(char *ins)
{
int s;
COD *x;
x = (COD*)malloc(sizeof(COD));
s = strlen(ins);
x->instruction = (char*)malloc((s+1)*sizeof(char));
strcpy(x->instruction,ins);
x->next = NULL;
return x;
}
void printList(COD *head)
{
COD *ptr;
for(ptr = head;ptr != NULL;ptr = ptr->next)
printf("\n%s\n",ptr->instruction);
}
The problem is with this line:
if(ptr->instruction == codop)
it compares address of strings not strings themselves.
Use strcmp or something like that instead.

can´t find element on a linked list

I have the next code, first i create a list from a file named hc12,and then i search the codop = "BLE" that has to be found on the list, but instead i keep getting the message COULDNT FIND CODOP. i dont know why, the linked list works well.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct nodo
{
char *code;
struct nodo *next;
}COD;
COD *createNodo(char *instruction);
void insertEnd(char *instruction,COD *last);
COD *lastElement(COD *head);
void remove(char *c);
void searchEndofLine(FILE *fd);
void ignoreSpaces(FILE *fd);
void CodopsList(COD *head);
char *OperandsTable(FILE *hc12);
COD *searchCodop(COD *head,char *codop);
int main()
{
COD *head = NULL,*found;
char *codop = "BLE";
CodopsList(head);
if((found = searchCodop(head,codop)) == NULL)
printf("COULDNT FIND CODOP");
else
printf("CODOP FOUND");
return 0;
}
void searchEndofLine(FILE *fd)
{
int car;
while((car = fgetc(fd))!= '\n')
;
}
void ignoreSpaces(FILE *fd)
{
int car;
do
{
car = fgetc(fd);
}while(car == '\t' || car == ' ');
}
void remove(char *c)
{
char *ptr;
if(((ptr=strchr(c,'\n'))!=NULL)||((ptr=strchr(c,'\t'))!=NULL)||((ptr=strchr(c,' '))!=NULL))
*ptr = '\0';
}
void CodopsList(COD *head)
{
int car;
FILE *hc12;
char *instruction;
COD *last;
if((hc12 = fopen("TABOP.txt","r"))!= NULL)
{
while((car = fgetc(hc12))!= EOF)
{
if(car != '\t')
{
instruction = OperandsTable(hc12);
if(head == NULL)
head = createNodo(instruction);
else
{
last = lastElement(head);
insertEnd(instruction,last);
}
}
else
searchEndofLine(hc12);
}
}
else
printf("Error\n");
}
char *OperandsTable(FILE *hc12)
{
int car,lon = 0,pos;
char *c;
fseek(hc12,-1,SEEK_CUR);
pos = ftell(hc12);
do
{
car = fgetc(hc12);
lon++;
}while(car != '\t');
fseek(hc12,pos,SEEK_SET);
c = (char*)calloc((lon+1),sizeof(char));
fgets(c,lon+1,hc12);
remove(c);
searchEndofLine(hc12);
return c;
}
void insertEnd(char *instruction,COD *last)
{
last->next = createNodo(instruction);
last->next->next = NULL;
last = last->next;
}
COD *lastElement(COD *head)
{
COD *ptr;
ptr = head;
while(ptr->next != NULL)
ptr = ptr->next;
return ptr;
}
COD *createNodo(char *instruction)
{
COD *x;
int t;
t = strlen(instruction);
x = (COD*)malloc(sizeof(COD));
x->codigo = (char*)malloc((t+1)*sizeof(char));
strcpy(x->code,instruction);
x->next = NULL;
return x;
}
COD *searchCodop(COD *head,char *codop)
{
COD *ptr;
for(ptr = head;ptr != NULL;ptr = ptr->next)
{
if(ptr->code == codop)
return ptr;
}
return NULL;
}
You should use strcmp instead of comparing two array pointers.
In searchCodop instead of
if(ptr->code == codop)
do
if (!strcmp(ptr->code, codop))
You are calling pointer as pass by value, instead use call by reference. For this, use pointer to pointer. Like that:
In main change
CodopsList(head);
with
CodopsList(&head);
And,
Change function
void CodopsList(COD *head)
with
void CodopsList(COD **head)
In function CodopsList use head as *head

Pointers and cstring beginner troubles

I have a problem with the function replace. What I want to accomplish is to replace some special characters, but I haven't written the code yet. So in the replace function we can at this moment just say that the function should print line for line the way I have tried to write. Can someone please correct this function? I can’t really get it
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct list_el {
char *ord;
int num;
struct list_el *prev;
struct list_el *next;
};
typedef struct list_el item;
struct list_el *head, *tail; /*Double linked list that makes it easier to add a element to the end of the FIFO list*/
void addNode(struct list_el *curr);
void readFile();
void print();
void replace();
void random();
void len();
int antE = 0;
int randint(int max)
{
int a = (max*rand()/(RAND_MAX+1.0));
return a;
}
int main(int argc, char *argv[]) {
item *curr;
struct list_el *pa;
if(argc == 3) {
readFile();
}
if(argc == 1) {
printf("Too few arguments, must bee 3");
} else if(strcmp(argv[1], "print") == 0) {
print();
} else if(strcmp(argv[1], "random") == 0) {
random();
} else if(strcmp(argv[1], "replace") == 0) {
replace();
} else if(strcmp(argv[1], "remove") == 0) {
printf("Random kommando kalt");
} else if(strcmp(argv[1], "len") == 0) {
len();
} else {
printf("Not a valid command");
}
if(argc == 3) {
free(curr);
}
}
void addNode(struct list_el *curr) {
if(head == NULL) {
head = curr;
curr->prev = NULL;
} else {
tail->next = curr;
curr->prev = tail;
}
tail = curr;
curr->next = NULL;
}
void readFile()
{
FILE *f = fopen("tresmaa.txt", "r");
if(f == 0) {
printf("Could not open file");
exit(8);
}
item *curr;
if(f != NULL) {
int antE = 0;
head = NULL;
char buffer[300];
while(fgets(buffer, 300-1,f) != NULL) {
curr = (item*)malloc(sizeof(item));
curr->ord = malloc(300);
curr->num = antE;
strcpy(curr->ord, buffer);
antE++;
addNode(curr);
}
}
fclose(f);
}
/*Traverserer listen og printer ut linje for lije
*/
void print()
{
item *curr;
printf("Print text:\n");
for(curr = head; curr != NULL; curr = curr->next) {
printf("%s", curr->ord);
}
}
/*Printer ut en tilfeldig setning
*/
void random()
{
item *curr;
int anum = randint(antE);
for(curr = head; curr != NULL; curr = curr->next) {
if(curr->num == anum) {
printf("Print a random line:\n%s", curr->ord);
}
}
}
void replace()
{
item *curr;
int i;
char tmp[300];
printf("Replace vowels ...\n");
printf("... with vowel 'a'\n");
for(curr = head; curr != NULL; curr = curr->next) {
strcpy(tmp, curr->ord);
for(i = 0; i < strlen(tmp); i++) {
printf("%s", tmp[i]);
}
}
}
void len()
{
item *curr;
long nc;
int i;
nc = 0;
for(curr = head; curr != NULL; curr = curr->next) {
nc += strlen(curr->ord);
}
printf("The text is %d characters long", nc);
}
If you just want to print the lines you can do it without the copying and extra loop:
for(curr = head; curr != NULL; curr = curr->next) {
printf("%s\n", curr->ord);
}
Your current code doesn't work because you tell printf with the %s format that its argument will be a string (aka. a pointer to a zero-terminated sequence of characters), but then you give it a single character, not such a pointer.

Resources