I am currently working on my assignment about a simple text editor that can open, add line and delete line and so and so...

I designed an algorithm to add new line to the doc and it works for the first time but didnt work after it, I dont know where the problems is(should be inside the function faddline), highly appreciate for your help :)

int fop(FILE *dfp)
{
    int l=1;
    char content[200];

    if( dfp == 0)
        printf("Unable to open file!\n");

    else
    {
        while(fgets(content,200,dfp)!= NULL)
        {
            printf("line %d: %s",l,content);
            l++;
        }
        printf("\n");
    }

    return l;
}

void faddline(FILE *fp,int line,char* content,int maxline,int *tipsy)
{
    int i=1,l=1;
    char dummy[200];
    FILE *stream;
    if(*tipsy==0)
    {
        stream = fopen("dummy.txt","w");

        while(fgets(dummy,200,fp)!=NULL)
        {
            if(i==line)
                fputs(content,stream);

            fputs(dummy,stream);
            i++;
        }
    }

    if(*tipsy==1)
    {
        stream = fopen("dummy.txt","a+");

        while(fgets(dummy,200,stream)!=NULL)
        {
            if(i==line)
                fputs(content,stream);

            i++;
        }
    }


    if(line>i)
        fputs(content,stream);

    fclose(stream);
    stream = fopen("dummy.txt","r");
    fop(stream);    
    (*tipsy) = 1;
}



    while(1)
    {
        printf("\nO)pen file    A)dd a line D)elete a line\nR)eplace word   S)ave file  Q)uit\nAction> ");
        gets(opt);

        switch(opt[0])
        {
            case('o'):
            case('O'):
                printf("Open file: ");

                gets(filepath);

                fp = fopen(filepath,"r");
                po = fop(fp);

                break;
            case('a'):
            case('A'):
                fp = fopen(filepath,"r");
                if(fp == 0)
                {
                    printf("Please open a file before editing!\n");
                    break;
                }

                printf("Add before line: ");
                scanf("%d", &line);

                printf("New line content: ");
                gets(dummy);
                gets(content);

                strcat(content,"\n");

                faddline(fp,line,content,po,&tipsy);

                break;

            default:
                printf("Invaild action!\n");
                break;
        }
    }

    return 0;
}

When you want to add a line to the end of a file you don't have to rewrite the file, just open with "a+", which will open the file for update and move the pointer to the end of the file. See more detailed description at this link.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.