I am programming a simple text editor in c and I defined a structure named node and created a linked list named textbuffer. I am trying to create an insert function for the text editor. Here is the code so far:
#include <stdio.h>
#include <string.h>
struct node
{
char statement[40];
int next;
};
struct node textbuffer[25];
int free_head;
int inuse_head;
void insert(int line, char* stat)
{
FILE *file;
file=fopen("texteditor.txt","w");
if(file!=NULL)
{
int i;
int k;
strcpy(textbuffer[line].statement,stat);
textbuffer[line].next=line+1;
fprintf(file,textbuffer[line].statement);
for(i=0;i<=25;i++)
{
if(textbuffer[i].statement==NULL)
{
free_head=i;
break;
}
}
for(k=0;k<=25;k++)
{
if(textbuffer[k].statement!=NULL)
{
inuse_head=k;
break;
}
}
}
else
{
printf("File couldn't found.");
}
fclose(file);
}
int main()
{
insert(1,"Hello World");
return 0;
}
The problem is when texteditor.txt file is empty and when i run the code it writes "Hello World" in the file, that's fine but when i run it for the second the, i am expecting it to write "HelloWorldHelloWorld" but it doesn't do anything.it's still staying as "Hello World". How can i solve this?
You can simply open the file in append mode:
file=fopen("texteditor.txt","a");
More info: https://en.cppreference.com/w/c/io/fopen