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.
Related
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;
}
I am having trouble understanding what I should do in the AddNumber function of my program. When the AddNumber function is called in main a pointer variable previous is created, and it takes the user's input and points it at the address of the variable newNum. I created an if statement for it to do that, but I was informed it doesn't do anything.
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
typedef struct A_NewNumber{
struct A_NewNumber *next;
double newNum;
} NewNumber;
NewNumber *AddNumber(NewNumber *previous, char *input){
//char input[16];
//double numEntered = 0;
NewNumber *newNum = malloc(sizeof(NewNumber));
sscanf(input, "%lf", &newNum->newNum);
//sscanf(input, "%s", newNum->enterNumber);
//numEntered = atof(input);
/*if (previous != NULL){
previous->newNum;
}*/
newNum->next = NULL;
newNum->newNum = 0;
return newNum;
}
void PrintList(NewNumber *start){
NewNumber *currentNumber = start;
int count = 0;
while(currentNumber != NULL){
count++;
printf("Numbers:%lf\n",
currentNumber->newNum);
currentNumber = currentNumber->next;
}
printf("Total Numbers Entered%d\n", count);
}
void CleanUp(NewNumber *start){
NewNumber *freeMe = start;
NewNumber *holdMe = NULL;
while(freeMe != NULL){
holdMe = freeMe->next;
free(freeMe);
freeMe = holdMe;
}
}
int main(){
//indexNum = 0;
char command[16];
char input[16];
//float userInput;
NewNumber *userEnter = NULL;
NewNumber *start = NULL;
NewNumber *newest = NULL;
while(fgets(input, sizeof input, stdin)){
printf("Please enter a number->");
printf("Enter 'quit' to stop or 'print' to print/calculate");
sscanf(input, "%s", command);
if(newest == NULL){
start = AddNumber(NULL, input);
newest = start;
}else{
newest = AddNumber(newest, input);
}if(strncmp(command, "print", 5) == 0){
PrintList(start);
}else if(strncmp(command, "quit", 4)== 0){
printf("\n\nQuitting....\n");
break;
//userInput = enterNumber;
}
}
CleanUp(start);
return 0;
}
}
It was not that bad, was just in need of a bit of clean-up.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// ALL CHECKS OMMITTED!
typedef struct A_NewNumber {
struct A_NewNumber *next;
double newNum;
} NewNumber;
NewNumber *AddNumber(NewNumber * previous, char *input)
{
int res;
// allocate new node
NewNumber *newNum = malloc(sizeof(NewNumber));
if (newNum == NULL) {
fprintf(stderr, "Malloc failed in AddNUmber()\n");
return previous;
}
// convert input string to float
res = sscanf(input, "%lf", &newNum->newNum);
if (res != 1) {
fprintf(stderr, "Something bad happend in AddNUmber()\n");
return previous;
}
// terminate that node
newNum->next = NULL;
// if this is NOT the first node
// put new node to the end of the list
if (previous != NULL) {
previous->next = newNum;
}
// return pointer to new node at end of the list
return newNum;
}
void PrintList(NewNumber * start)
{
NewNumber *currentNumber = start;
int count = 0;
while (currentNumber != NULL) {
count++;
printf("Numbers:%lf\n", currentNumber->newNum);
currentNumber = currentNumber->next;
}
printf("Total Numbers Entered %d\n", count);
}
void CleanUp(NewNumber * start)
{
NewNumber *freeMe = start;
NewNumber *holdMe = NULL;
while (freeMe != NULL) {
holdMe = freeMe->next;
free(freeMe);
freeMe = holdMe;
}
}
int main()
{
char input[16];
NewNumber *start = NULL;
NewNumber *newest = NULL;
int res;
// infinite loop
while (1) {
// give advise
printf("Please enter a number or\n");
printf("'quit' to stop or 'print' to print/calculate\n");
// get input from user
res = scanf("%s", input);
if (res != 1) {
if (res == EOF) {
fprintf(stderr, "Got EOF, bailing out\n");
break;
} else {
fprintf(stderr, "something bad happend, bailing out\n");
break;
}
}
// check if a command was given
if (strncmp(input, "print", 5) == 0) {
PrintList(start);
continue;
} else if (strncmp(input, "quit", 4) == 0) {
printf("\n\nQuitting....\n");
break;
}
// otherwise gather numbers
if (newest == NULL) {
start = AddNumber(NULL, input);
if (start == NULL) {
fprintf(stderr, "AddNumber returned NULL\n");
break;
}
newest = start;
} else {
newest = AddNumber(newest, input);
if (newest == NULL) {
fprintf(stderr, "AddNumber returned NULL\n");
break;
}
}
}
CleanUp(start);
return 0;
}
You should really make a habit of checking all returns and if you don't: be able to give a good reason why you didn't.
Don't forget to switch on all warnings your compiler offers. Even if you don't understand them now, Google might have an answer and if not some people here do (in that order, thank you).
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Ok so what I have right now, checks the counts of the words. But I am having trouble trying to sort the words alphabetically.
I'd rather do that then just count the number of which they are.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node *node_ptr;
typedef struct node {
int count;
char *word;
node_ptr next;
} node_t;
char *words[] = { "hello", "goodbye", "sometimes", "others", "hello", "others", NULL };
node_ptr new_node() {
node_ptr aNode;
aNode = (node_ptr)(malloc(sizeof(node_t)));
if (aNode) {
aNode->next = (node_ptr)NULL;
aNode->word = (char *)NULL;
aNode->count = 0;
}
return aNode;
}
node_ptr add_word(char *word, node_ptr theList) {
node_ptr currPtr, lastPtr, newPtr;
int result;
int found = 0;
currPtr = theList;
lastPtr = NULL;
printf("Checking word:%s\n", word);
if (!currPtr) {
newPtr = new_node();
if (!newPtr) {
fprintf(stderr, "Fatal Error. Memory alloc error\n");
exit(1);
}
newPtr->word = word;
newPtr->next = currPtr;
newPtr->count = 1;
found = 1;
theList = newPtr;
}
while (currPtr && !found) {
result = strcmp(currPtr->word, word);
if (result == 0) {
currPtr->count += 1;
found = 1;
} else
if (result>0) {
newPtr = new_node();
if (!newPtr) {
fprintf(stderr, "Fatal Error. Memory alloc error\n");
exit(1);
}
newPtr->word = word;
newPtr->next = currPtr;
newPtr->count = 1;
if (lastPtr) {
lastPtr->next = newPtr;
} else {
theList = newPtr;
}
found = 1;
} else {
lastPtr = currPtr;
currPtr = currPtr->next;
}
}
if ((!found) && lastPtr) {
newPtr = new_node();
if (!newPtr) {
fprintf(stderr, "Fatal Error. Memory alloc error\n");
exit(1);
}
newPtr->word = word;
newPtr->next = (node_ptr)NULL;
newPtr->count = 1;
lastPtr->next = newPtr;
found = 1;
}
return theList;
}
void printList(node_ptr theList) {
node_ptr currPtr = theList;
while (currPtr) {
printf("word: %s\n", currPtr->word);
printf("count: %d\n", currPtr->count);
printf("---\n");
currPtr = currPtr->next;
}
}
int main() {
char **w = words;
node_ptr theList = (node_ptr)NULL;
printf("Start\n");
while (*w) {
theList = add_word(*w, theList);
w++;
}
printList(theList);
printf("OK!\n");
return 0;
}
I'd also like to instead of reading from an array of words, I'd rather read from a file.
FILE *fp;
fp = fopen("some.txt", "w");
How do I read from a file using my structure I've created and then sort them?
You can read the words from a file with fscanf():
int main(int argc, char *argv[]) {
node_t *theList = NULL;
for (int i = 1; i < argc; i++) {
FILE *fp = fopen(argv[i], "r");
if (fp != NULL) {
char word[100];
while (fscanf(fp, "%99s", word) == 1) {
theList = add_word(word, theList);
}
fclose(fp);
}
}
printList(theList);
printf("OK!\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
struct treeNode
{
char *word;
int NumberCnt;
struct treeNode *rightPTR, *leftPTR;
};
typedef struct treeNode node;
node *rootPTR = NULL;
void freeTree(node *currPTR)
{
if (currPTR!= NULL)
{
freeTree(currPTR -> leftPTR);
free(currPTR);
freeTree(currPTR -> rightPTR);
}
}
void printTree(node *currPTR)
{
if (currPTR != NULL)
{
printTree(currPTR ->leftPTR);
printf("%s appeared:%d times\n", currPTR->word, currPTR->NumberCnt);
printTree(currPTR ->rightPTR);
}
}
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = input;
tempPTR -> NumberCnt=0;
tempPTR -> leftPTR = NULL;
tempPTR -> rightPTR = NULL;
if (rootPTR == NULL)
{
rootPTR = tempPTR;
rootPTR -> NumberCnt++;
}
else
{
node *currPTR = rootPTR;
node *prevPTR = NULL;
while (currPTR != NULL)
{
int comp = strcmp(input, (currPTR->word));
if (comp == 0)
{
printf ("Entry already exists\n");
currPTR->NumberCnt++;
return 1;
}
else if (comp < 0)
{
prevPTR = currPTR;
currPTR = currPTR->leftPTR;
}
else if (comp > 0)
{
prevPTR = currPTR;
currPTR = currPTR->rightPTR;
}
}
int comp = strcmp(input, (prevPTR ->word));
if (comp < 0)
{
prevPTR->leftPTR = tempPTR;
prevPTR ->NumberCnt++;
}
else if (comp > 0)
{
prevPTR->rightPTR = tempPTR;
prevPTR->NumberCnt++;
}
return 0;
}
printf("root1%s\n",rootPTR->word);
return 2;
}
int search(char* input)
{
if (input == rootPTR ->word)
{
printf("Node found %s\n", rootPTR->word);
return 0;
}
else
{
if (input < rootPTR ->word)
{
node *currPTR = rootPTR->leftPTR;
while (currPTR != NULL)
{
if (input == currPTR->word)
{
printf("Node found %s\n", currPTR->word);
return 0;
}
else if (input < currPTR->word)
{
currPTR = (currPTR -> leftPTR);
}
else if (input > currPTR->word)
{
currPTR = (currPTR -> rightPTR);
}
}
printf ("Node not in tree\n");
return 1;
}
if (input > rootPTR ->word)
{
node *currPTR = rootPTR->rightPTR;
while (currPTR != NULL)
{
if (input == currPTR->word)
{
printf ("Node found %s\n", currPTR->word);
return 0;
}
else if (input < currPTR->word)
{
currPTR = (currPTR -> leftPTR);
}
else if (input > currPTR->word)
{
currPTR = (currPTR ->rightPTR);
}
}
printf ("Node not in tree\n");
return 1;
}
}
return 2;
}
void fixWord(char* buff)
{
char* unfixed = buff;
char* fixed = buff;
while (*unfixed)
{
if (isalpha(*unfixed))
{
*fixed=tolower(*unfixed);
*fixed++;
}
*unfixed++;
}
*fixed=0;
}
int main()
{
FILE *ptr_file;
char buff [100];
//ptr_file = fopen ("sherlock.txt", "r");
ptr_file = fopen ("input.txt", "r");
if (!ptr_file)
printf("File read error");
while(fscanf(ptr_file, "%s ", buff ) != EOF)
{
int comparison = strcmp(buff, "endoffile");
if (comparison == 0)
{
return 0;
}
fixWord(buff);
insertNode(buff);
}
fclose(ptr_file);
printf("root:%s\n", rootPTR->word);
return 0;
}
Ok I have this binary tree which is taking string inputs from a file. It works if I pass strings directly to the tree, however when I attempt to pass it the strings I read in form the file it keeps on replacing the root node and does not add them correctly to the tree.
buff is current line value and overwritten on each line reading:
insertNode(buff);
insertNode assigns overwriten buffer.
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = input;
....
So, you should dynamic allocation for input value as:
int insertNode (char* input)
{
node *tempPTR = malloc(sizeof(node));
tempPTR -> word = strdup(input);
....
You're passing buff to your insert function, and it's storing that in the node. So all your nodes will end up pointing to the same address, that of buff in main.
You need to allocate storage for each string in each node, and copy your input into that. And remember to deallocate properly when you delete your tree.
strdup can be handy for that if your library has it.
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.