0

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?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Oğulcan
  • 17
  • 4
  • 2
    Take a look at the different modes you can use when opening a file. https://en.cppreference.com/w/cpp/io/c/fopen The `"w"` mode destroys the contents of an existing file. – Retired Ninja May 26 '21 at 20:57
  • You're linking with index instead of pointers. Interesting. I've never seen it and never even thought about the possibility. Any particular reason? – klutt May 26 '21 at 21:07

1 Answers1

1

You can simply open the file in append mode:

file=fopen("texteditor.txt","a");

More info: https://en.cppreference.com/w/c/io/fopen

HARSH MITTAL
  • 750
  • 4
  • 17