[英]Text Editor in C select text with shift
我正在嘗試使用C設計文本編輯器。例如,我正在創建一個新的文本文件,並從用戶那里獲取內容,直到按為止.
void Create() {
fp1 = fopen("temp.txt", "w");
printf("\n\tEnter the text and press '.' to save\n\n");
while (1) {
c = getchar();
fputc(c, fp1);
if (c == '.') {
fclose(fp1);
printf("\n\tEnter then new filename: ");
scanf("%s", fn);
fp1 = fopen("temp.txt", "r");
fp2 = fopen(fn, "w");
while (!feof(fp1)) {
c = getc(fp1);
putc(c, fp2);
}
fclose(fp2);
break;
}
}
}
到這里一切都很好,我的問題是我希望用戶可以使用Shift鍵選擇文本並使用向上/向下箭頭瀏覽文本...
這里的一切都不好。 您的程序有多個問題:
c
, fp1
, fp2
, fn
... scanf()
。 stdin
讀取時,您無需檢查EOF
。 .
進入temp.txt
.
因為最終標記會產生副作用:您將無法在文件中使用該字符,這是一個嚴格的限制。 您至少應該只考慮.
在一行的開頭。 這是一個改進的版本:
int Create(void) {
FILE *fp1, *fp2;
char fn[1024];
int last = '\n', c;
fp1 = fopen("temp.txt", "w+");
if (fp1 == NULL) {
printf("Cannot create file temp.txt\n");
return -1;
}
printf("\n\tEnter the text and press '.' to save\n\n");
while ((c = getchar()) != EOF && (c != '.' || last != '\n')) {
fputc(c, fp1);
last = c;
}
for (;;) {
printf("\n\tEnter then new filename: ");
if (scanf(" %1023[^\n]%*c", fn) != 1) {
printf("input error\n");
fclose(fp1);
return -2;
}
fp2 = fopen(fn, "w");
if (fp2 == NULL) {
printf("Cannot create output file %s\n", fn);
} else {
break;
}
}
rewind(fp1);
while ((c = getc(fp1)) {
putc(c, fp2);
}
fclose(fp2);
fclose(fp1);
return 0;
}
如果要編寫交互式編輯器,則需要使用stty()
將終端設置為原始模式,並使用ncurses
的庫來處理全屏輸出和光標鍵輸入。 您還可以假定終端支持ANSI轉義序列以及相應的硬代碼輸入和輸出。
這樣的項目是相當努力的。 我強烈建議您查看現有的開源編輯器,閱讀源代碼並了解它們如何處理各種任務。 我本人與人合着了一個名為qemacs
的Emacs克隆(適用於Quick Emacs)。 您可以閱讀有關內容,並從http://qemacs.org獲取源代碼,但這是一個面向初學者的大型項目。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.