簡單的寫了一個文字編輯器,功能很簡單,但足以把檔案IO相關的操作熟悉了,可能功能或者分配的大小還不夠完善。請參考參考:
#include <stdio.h>#include <conio.h>#include <stdlib.h>#include <string.h>#include <windows.h>#include <fcntl.h>int count ;char ch = 0;char file_name[20]={0};char buffer[1024*1024]={0};//退出文字編輯器int exit_editor(){ printf("exit editor!\n"); memset(buffer, 0,1024*1024); system("cls"); return -1 ;}//文本編輯模式int text_editor_mode(){ int flag ; char input_ch = 0 ; flag = 0 ; count = 0 ; system("cls"); //進入編輯文字模式 printf("\a"); //清空數組 while(1) { input_ch = getch(); //ESC按鍵 if(input_ch == 0x1B) { printf("exit editor\n"); system("cls"); flag = 1 ; return flag ; } //ENTER按鍵---->實現文字編輯器換行 if(input_ch == 0x0d) { putchar('\n'); } //輸入的內容不是ESC按鍵的情況下就將文本資訊儲存到數組裡去 if(input_ch != 0x1B) { buffer[count] = input_ch ; putchar(input_ch); count++; } }}//文本儲存模式int save_text_mode(){ int flag ; flag = 0 ; system("cls"); printf("plase input file name\n"); scanf("%s",file_name); int openfd = open(file_name,O_CREAT | O_TRUNC | O_RDWR); if(-1 == openfd){ printf("open file fair!\n"); memset(buffer, 0,1024*1024); memset(file_name,0,20); return -1 ; } write(openfd,buffer,count); printf("save file success\n"); memset(buffer, 0,1024*1024); memset(file_name,0,20); close(openfd); printf("file save success!file_name:%s\n",file_name); system("cls"); flag = 1 ; return flag ;}//讀取一個檔案的資訊int read_file(){ char *file = NULL; char *file_buffer = NULL ; system("cls"); int fle_flag = 0 ; int count_fd ; file = malloc(20); file_buffer = malloc(1024); printf("please input file name!\n"); scanf("%s",file); system("cls"); printf("please input file size!\n"); scanf("%d",&count_fd); int fd = open(file,O_RDONLY); if(-1 == fd) fprintf(stderr,"open file error"); system("cls"); int i ; read(fd,file_buffer,count_fd); for(i = 0 ; i < count_fd ; i++) { printf("%c",file_buffer[i]); } while(1) { char rch = getch(); if(rch == 0x1B){ system("cls"); break ; } } free(file); free(file_buffer); close(fd); fle_flag = 1 ; return fle_flag ;}int main(void){ int file_fd = -1; int ret = 0; int exit_ret = 0; int save_ret = 0; int read_ret = 0 ; //重新開始 Rep: printf("Welcome to yyx develop VIM-EDITUO\n"); printf("please input i to editor ,r to read , w to save , q to quit\n"); while(1) { ch = getch(); switch(ch) { case 'w': save_ret = save_text_mode(); break ; case 'i': ret = text_editor_mode(); break ; case 'q': exit_ret = exit_editor(); break ; case 'r': read_ret = read_file(); break ; } if(ret == 1 || save_ret == 1 || read_ret == 1) goto Rep ; if(exit_ret == -1) break ; } return 0 ;}