Files
degvi/Text.c
2013-01-31 07:30:12 +09:00

150 lines
2.6 KiB
C

#include "init.h"
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "Text.h"
Text Text_create(void)
{
Text this;
this = malloc(sizeof(struct Text_struct));
if (this == NULL) {
fprintf(stderr, "malloc failed\n");
exit(EXIT_FAILURE);
}
this->maxSize = 0;
this->size = 0;
this->lines = NULL;
return this;
}
void Text_destroy(Text this)
{
int i;
if (this == NULL) {
return;
}
for (i = 0; i < this->size; i++) {
Line_destroy(*(this->lines + i));
}
free(this);
}
int Text_size(Text this)
{
return this->size;
}
Line Text_getLine(Text this, int index)
{
assert(index >= 0 && index < this->size);
return *(this->lines + index);
}
void Text_addLine(Text this, int index, Line value)
{
assert(index >= 0 && index <= this->size);
if (this->size + 1 > this->maxSize) {
this->maxSize += TEXT_BUFFER_INCREMENT_SIZE;
this->lines = realloc(this->lines, sizeof(Line) * this->maxSize);
if (this->lines == NULL) {
fprintf(stderr, "realloc failed\n");
exit(EXIT_FAILURE);
}
}
if (index < this->size) {
memmove(this->lines + index + 1, this->lines + index, sizeof(Line) * (this->size - index));
}
*(this->lines + index) = value;
this->size++;
}
Line Text_removeLine(Text this, int index)
{
Line line;
assert(index >= 0 && index < this->size);
line = Text_getLine(this, index);
memmove(this->lines + index, this->lines + index + 1, sizeof(Line) * (this->size - index - 1));
this->size--;
return line;
}
void Text_load(Text this, char *filename)
{
FILE *fp;
Line line;
Character c;
fp = fopen(filename, "r");
if (fp == NULL) {
fprintf(stderr, "fopen failed\n");
exit(EXIT_FAILURE);
}
line = Line_create();
while (!Character_isEndOfFile(c = Character_read(fp))) {
if (c == '\n') {
Text_addLine(this, Text_size(this), line);
line = Line_create();
} else {
Line_addCharacter(line, Line_size(line), c);
}
}
if (Line_size(line) > 0) {
Text_addLine(this, Text_size(this), line);
}
fclose(fp);
}
void Text_save(Text this, char *filename)
{
FILE *fp;
int j;
fp = fopen(filename, "w");
if (fp == NULL) {
fprintf(stderr, "fopen failed\n");
exit(EXIT_FAILURE);
}
for (j = 0; j < this->size; j++) {
Line line;
int i;
line = Text_getLine(this, j);
for (i = 0; i < Line_size(line); i++) {
char buf[6 + 1];
Character_toString(Line_getCharacter(line, i), buf);
if (fputs(buf, fp) == EOF) {
fprintf(stderr, "fputs failed\n");
exit(EXIT_FAILURE);
}
}
if (fputc('\n', fp) == EOF) {
fprintf(stderr, "fputc failed\n");
exit(EXIT_FAILURE);
}
}
fclose(fp);
}