new demo
This commit is contained in:
+16
-24
@@ -8,26 +8,27 @@ int
|
||||
fileCountLines(file_t* f) {
|
||||
char ch;
|
||||
int lines = 0;
|
||||
FILE* fd = fopen(f->path, "r");
|
||||
|
||||
while ((ch = fgetc(f->descriptor)) != EOF) {
|
||||
while ((ch = fgetc(fd)) != EOF) {
|
||||
if (ch == '\n') {
|
||||
lines++;
|
||||
}
|
||||
}
|
||||
|
||||
rewind(f->descriptor);
|
||||
fclose(fd);
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
||||
void
|
||||
_fileLoadLines(file_t* f) {
|
||||
_fileLoadLines(file_t* f, FILE* fd) {
|
||||
int lineLength;
|
||||
char ch;
|
||||
vector_t* line = vectorInit(CHAR);
|
||||
|
||||
for (int i = 0; i < f->length; i++) {
|
||||
while ((ch = fgetc(f->descriptor)) != '\n' && ch != EOF) {
|
||||
while ((ch = fgetc(fd)) != '\n' && ch != EOF) {
|
||||
vectorPush(line, &ch);
|
||||
}
|
||||
|
||||
@@ -40,8 +41,6 @@ _fileLoadLines(file_t* f) {
|
||||
vectorPush(f->lines, line);
|
||||
line = vectorInit(CHAR);
|
||||
}
|
||||
|
||||
rewind(f->descriptor);
|
||||
}
|
||||
|
||||
char*
|
||||
@@ -50,40 +49,34 @@ fileToString(file_t* f) {
|
||||
}
|
||||
|
||||
file_t*
|
||||
fileInit(char* path, char* mode) {
|
||||
fileInit(char* path) {
|
||||
file_t* f = malloc(sizeof(file_t));
|
||||
if (f == NULL) {
|
||||
perror("failed to allocate memory for the file\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
f->lines = malloc(sizeof(vector_t));
|
||||
if (f->lines == NULL) {
|
||||
perror("failed to allocate memory for the file contents vector\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
int imode = 0;
|
||||
|
||||
if (strcmp(mode, "r") == 0) {
|
||||
imode = 0;
|
||||
} else if (strcmp(mode, "w") == 0) {
|
||||
imode = 1;
|
||||
} else if (strcmp(mode, "a") == 0) {
|
||||
imode = 2;
|
||||
} else {
|
||||
perror("only allowed modes for file opening are \"r\", \"w\" and \"a\"\n");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
f->path = path;
|
||||
|
||||
f->descriptor = fopen(path, mode);
|
||||
if (f->descriptor == NULL) {
|
||||
fprintf(stderr, "unable to open file %s with mode %s\n", path, mode);
|
||||
FILE* fd = fopen(f->path, "r");
|
||||
if (fd == NULL) {
|
||||
fprintf(stderr, "unable to open file %s with mode \"r\"\n", path);
|
||||
fclose(fd);
|
||||
fileCleanup(f);
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
f->length = fileCountLines(f);
|
||||
f->lines = vectorInit(VECTOR); // vector of vectors of chars = vector of strings
|
||||
if (imode == 0) _fileLoadLines(f);
|
||||
_fileLoadLines(f, fd);
|
||||
|
||||
fclose(fd);
|
||||
|
||||
return f;
|
||||
}
|
||||
@@ -91,7 +84,6 @@ fileInit(char* path, char* mode) {
|
||||
void
|
||||
fileCleanup(file_t* f) {
|
||||
vectorCleanup(f->lines);
|
||||
fclose(f->descriptor);
|
||||
free(f);
|
||||
}
|
||||
|
||||
@@ -102,4 +94,4 @@ filePrint(file_t* f) {
|
||||
line = (vector_t *)vectorGetAt(f->lines, i);
|
||||
vectorPrintAsString(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user