Save the file

This commit is contained in:
Aaron Fischer 2018-10-05 11:50:02 +02:00
parent 66b97546e2
commit 1abad8b71f

54
kilo.c
View file

@ -6,6 +6,7 @@
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
@ -63,6 +64,10 @@ struct editorConfig {
struct editorConfig E;
/*** prototypes ***/
void editorSetStatusMessage(const char *fmt, ...);
/*** terminal ***/
void die(const char *s) {
@ -255,6 +260,26 @@ void editorInsertChar(int c) {
/*** file i/o ***/
char *editorRowsToString(int *buflen) {
int totlen = 0;
int j;
for (j=0; j<E.numrows; j++) {
totlen += E.row[j].size + 1;
}
*buflen = totlen;
char *buf = malloc(totlen);
char *p = buf;
for (j=0; j<E.numrows; j++) {
memcpy(p, E.row[j].chars, E.row[j].size);
p += E.row[j].size;
*p = '\n';
p++;
}
return buf;
}
void editorOpen(char *filename) {
free(E.filename);
E.filename = strdup(filename);
@ -275,6 +300,29 @@ void editorOpen(char *filename) {
fclose(fp);
}
void editorSave() {
if (E.filename == NULL) return;
int len;
char *buf = editorRowsToString(&len);
int fd = open(E.filename, O_RDWR | O_CREAT, 0644);
if (fd != -1) {
if (ftruncate(fd, len) != -1) {
if (write(fd, buf, len) == len) {
close(fd);
free(buf);
editorSetStatusMessage("%d bytes written to disk", len);
return;
}
}
close(fd);
}
free(buf);
editorSetStatusMessage("Can't save! I/O error: %s", strerror(errno));
}
/*** append buffer ***/
struct abuf {
@ -466,6 +514,10 @@ void editorProcessKeypress() {
exit(0);
break;
case CTRL_KEY('s'):
editorSave();
break;
case HOME_KEY:
E.cx = 0;
break;
@ -539,7 +591,7 @@ int main(int argc, char *argv[]) {
editorOpen(argv[1]);
}
editorSetStatusMessage("HELP: Ctrl-Q = Quit");
editorSetStatusMessage("HELP: Ctrl-S = save | Ctrl-Q = Quit");
while (1) {
editorRefreshScreen();