4

I have the following problem:

How I can print text in my program, so that I can edit it?

For example, program print to stdout:

C:\\BlaBlaBla\file.txt

And I can push backspace, that edit this text:

C:\\BlaBlaBla\file_1.txt

I will be glad of any information.

Konstantin Dedov
  • 427
  • 3
  • 12

2 Answers2

0

One way to get command line editing is to use the functionality provided by the GNU readline library.

JohnH
  • 2,713
  • 12
  • 21
0

I solved this problem in this way using malloc (use backspace, delete and arrows (left and right)):

#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <malloc.h>


#define ENTER 13
#define ARROW 224
#define LEFT 75
#define RIGHT 77
#define SEPARATOR 219
#define DELETE 83
#define BACKSPACE 8

void editText(char *s);
void printTextWithCursor(char *s, size_t position);
int insertInStr(char **s, size_t position, char c);
void deleteSymbol(char *s, size_t position);

#define TEXT "Some text."

int main()
{
    unsigned char c;
    char *s = malloc(strlen(TEXT)+1);
    __int64 pos;

    strcpy(s, TEXT);
    pos = strlen(s);

    printf("The original text:"TEXT"\n");
    printf(TEXT"%c", SEPARATOR);


    while((c = getch())!= ENTER)
    {
        putchar('\r');
        switch(c)
        {
        case ARROW://OR DELETE
            c = getch();
            if (c == LEFT && pos > 0)
                pos--;
            if (c == RIGHT && pos < strlen(s))
                pos++;
            if(c == DELETE && pos < strlen(s))
                deleteSymbol(s, pos);
            break;
        case BACKSPACE:
            if(pos > 0)
                deleteSymbol(s, --pos);
            break;
        default:
            if(pos >= 0 && pos <= strlen(s))
            {
                insertInStr(&s, pos++, c);
            }


        }
        printTextWithCursor(s, pos);

    }

    return 0;
}

void deleteSymbol(char *s, size_t position)
{
    size_t i, len = strlen(s);

    for(i = position; i < len; i++)
        s[i] = s[i+1];
}
int insertInStr(char **s, size_t position, char c)
{
    __int64 i;

    if((*s = realloc(*s, strlen(*s) +1 +1)) == 0)
        return 0;
    for(i = strlen(*s)+1; i >= position; i--)
        (*s)[i] = i == position ? c : (*s)[i-1];
    return 1;
}
void printTextWithCursor(char *s, size_t position)
{
    size_t currPos, length = strlen(s);;


    for(currPos = 0; currPos <= length; currPos++)
    {
        putchar(currPos < position ? s[currPos] : currPos == position ? SEPARATOR : s[currPos-1]);
    }
    putchar('\0');
}
Konstantin Dedov
  • 427
  • 3
  • 12