73 lines
1.9 KiB
C
73 lines
1.9 KiB
C
#define _DEFAULT_SOURCE
|
|
#define _BSD_SOURCE
|
|
#define _GNU_SOURCE
|
|
|
|
#include <errno.h> // for errno
|
|
#include <fcntl.h> // for open, O_CREAT, O_RDWR
|
|
#include <stdio.h> // for NULL, fclose, fopen, FILE
|
|
#include <stdlib.h> // for free
|
|
#include <string.h> // for strdup, strerror
|
|
#include <unistd.h> // for close, ftruncate, ssize_t
|
|
#include <termios.h> // for termios
|
|
|
|
#include "file.h"
|
|
#include "fn.h" // for editorSetStatusMessage, E, editorConfig, edito...
|
|
#include "hl.h" // for editorSelectSyntaxHighlight
|
|
#include "row.h" // for editorRowsToString
|
|
#include "terminal.h" // for die
|
|
|
|
void editorOpen(char *filename) {
|
|
free(E.filename);
|
|
// TODO: Maybe replace strdup (string.h), becaus it is no strict posix c lib
|
|
E.filename = strdup(filename);
|
|
|
|
editorSelectSyntaxHighlight();
|
|
|
|
FILE *fp = fopen(filename, "r");
|
|
if (!fp) die("fopen");
|
|
|
|
char *line = NULL;
|
|
size_t linecap = 0;
|
|
ssize_t linelen;
|
|
while ((linelen = getline(&line, &linecap, fp)) != -1) {
|
|
while (linelen > 0 && (line[linelen - 1] == '\n' ||
|
|
line[linelen - 1] == '\r'))
|
|
linelen--;
|
|
editorInsertRow(E.numrows, line, linelen);
|
|
}
|
|
free(line);
|
|
fclose(fp);
|
|
E.dirty = 0;
|
|
}
|
|
|
|
void editorSave() {
|
|
if (E.filename == NULL) {
|
|
E.filename = editorPrompt("Save as: %s (ESC to cancel)", NULL);
|
|
if (E.filename == NULL) {
|
|
editorSetStatusMessage("Save aborted");
|
|
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);
|
|
E.dirty = 0;
|
|
editorSetStatusMessage("%d bytes written to disk", len);
|
|
return;
|
|
}
|
|
editorSelectSyntaxHighlight();
|
|
}
|
|
close(fd);
|
|
}
|
|
|
|
free(buf);
|
|
editorSetStatusMessage("Can't save! I/O error: %s", strerror(errno));
|
|
}
|