Implementing a Simple Text Editor in C Language
In this article, we will implement a simple text editor using the C language. This editor will be able to read, display, and save text files, making it suitable for beginners to understand basic file operations and string handling.
Requirements Analysis
We aim to implement the following basic functionalities:
- Open and read a text file.
- Display the file content.
- Allow users to perform basic content addition and modification operations.
- Save changes made to the file.
Program Structure
To make the code reasonable and easy to understand, we will divide the program into several parts:
- Read file content
- Display content
- Modify or add content
- Save changes to the file
Below is the complete code example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LINES 1000
#define MAX_LENGTH 256
char *lines[MAX_LINES];
int line_count = 0;
void read_file(const char *filename) {
FILE *file = fopen(filename, "r");
if (!file) {
printf("Cannot open file %s\n", filename);
return;
}
while (line_count < MAX_LINES && fgets(lines[line_count], MAX_LENGTH, file)) {
lines[line_count][strcspn(lines[line_count], "\n")] = '\0'; // Remove newline character
line_count++;
}
fclose(file);
}
void display_content() {
printf("Current document content:\n");
for (int i = 0; i < line_count; i++) {
printf("%d: %s\n", i + 1, lines[i]);
}
}
void modify_content() {
int line_num;
char new_text[MAX_LENGTH];
printf("Please enter the line number to modify: ");
scanf("%d", &line_num);
if (line_num <= 0 || line_num > line_count) {
printf("Invalid line number, please try again.\n");
return;
}
getchar(); // Clear newline character from input buffer
printf("Please enter the new text: ");
fgets(new_text, MAX_LENGTH, stdin); // Remove newline character from new input
new_text[strcspn(new_text, "\n")] = '\0';
strcpy(lines[line_num - 1], new_text); // Update specified line text
}
void add_content() {
char new_line[MAX_LENGTH];
if (line_count >= MAX_LINES) {
printf("Maximum line count reached, cannot add new line.\n");
return;
}
getchar(); // Clear newline character from input buffer
printf("Please enter a new line of text: ");
fgets(new_line, MAX_LENGTH, stdin); // Remove newline character from new input
new_line[strcspn(new_line, "\n")] = '\0';
strcpy(lines[line_count], new_line); // Add a new valid value at the last non-empty position and update count
line_count++;
}
void save_file(const char *filename) {
FILE *file = fopen(filename, "w");
if (!file) {
printf("Cannot save to file %s\n", filename);
return;
}
for (int i = 0; i < line_count; ++i) {
fprintf(file, "%s\n", lines[i]);
}
fclose(file);
printf("Save successful!\n");
}
int main(int argc, const char **argv) {
if(argc != 2) {
printf ("Usage: %s filename.txt\n", argv[0]);
return EXIT_FAILURE;
}
for(int j=0; j<MAX_LINES; j++) {
lines[j] =(char*)malloc(MAX_LENGTH*sizeof(char));
memcpy(lines[j], " ", sizeof(char));
}
read_file(argv[1]);
int option;
do {
display_content();
printf("\nSelect operation:\n");
printf("1 - Modify content\n");
printf("2 - Add new line\n");
printf("3 - Save changes\n");
printf("-1 - Exit\n");
printf("n:");
scanf("%d", &option);
switch(option) {
case 1:
modify_content();
break;
case 2:
add_content();
break;
case 3:
save_file(argv[1]);
break;
}
} while(option != -1);
for(int m=0; m<MAX_LINES; m++) {
free(lines[m]);
}
return EXIT_SUCCESS;
}
Analysis and Explanation
Initialization and Resource Management
Dynamic memory allocation is used for each line segment (i.e., each line as a string). In the <span>main</span>
function, all variables are initialized, and the specified document is loaded based on the passed parameters.
Method Details
<span>read_file</span>
- Function: Opens a text file from the given path and reads each line as a string into an array. Here, fgets is used to avoid overflow, and the buffer is cleared after reading.
<span>display_content</span>
- Function: Iterates through the stored strings and outputs them to the console in a formatted manner, helping users to view the current document status instantly.
<span>modify_content</span>
- Function: Users provide the data to be modified, specifying a particular record. By using a number, it allows for replacement of that record to reflect the updated state. Validity of the number must also be ensured to correctly index the corresponding element.
<span>add_content</span>
- Function: The new port can add a character to the existing list, adjusting the current active data type. It only requires incrementing the counter and confirming before writing. Quick judgment protection measures are also in place for adverse effects such as exceeding limits.
<span>save_file</span>
- Function: Accepts the latest data and writes it back to disk to ensure persistence. Not saving would result in losing the previous process information, and it can also provide feedback on successful logical processing, enhancing the interactive experience!
Using the above simple framework, we have completed the basic paragraph text editing process! I hope this article helps you further understand the functionalities and applications of C language programs. I believe that as your skills continue to improve, the scope of applications will expand. If you have any questions, feel free to engage in further discussions and research.