Everything is not fine here. Your program has multiple issues:
- You do not define
c
, fp1
, fp2
, fn
...
- You use
scanf()
in an unsafe way.
- You dont check for
EOF
when reading from stdin
.
- You store the
.
into temp.txt
- Also check Why is “while ( !feof (file) )” always wrong?
- Using a single character
.
as the final mark has side effects: you will not be able to use that character in the file, that's a strong limitation. You should at least only consider .
at the start of a line.
Here is an improved version:
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;
}
If you wish to write an interactive editor, you need to set the terminal in raw mode with stty()
and use a library such as ncurses
to handle full screen output and cursor key input. You can also assume the terminal supports ANSI escape sequences and hard code input and output accordingly.
Such a project is quite an endeavor. I strongly suggest you look at existing open source editors, read the source code and learn how they handle various tasks. I personally co-authored an Emacs clone called qemacs
(for Quick Emacs). You can read about it and get the source code from http://qemacs.org, but it is a large project to tackle for a beginner.