made work: copy a file, move a file, check if a file exists, delete a file

This commit is contained in:
Odweta
2023-12-23 19:51:54 +01:00
parent 29e1815e5b
commit 490a7cc973
8 changed files with 150 additions and 35 deletions
+62 -1
View File
@@ -10,7 +10,7 @@ fileCountLines(file_t* f) {
int lines = 0;
FILE* fd = fopen(f->path, "r");
if (!fd) {
fprintf(stderr, "unable to open file");
fprintf(stderr, "unable to count lines in file %s\n", f->path);
exit(EXIT_FAILURE);
}
@@ -70,6 +70,22 @@ fileToString(file_t* f) {
return (char *)vectorToString(f->lines);
}
int
fileExists(file_t* f) {
FILE* fd = fopen(f->path, "r");
if (!fd) {
return 0; // file does not exist
} else {
return 1; // file exists
}
fclose(fd);
}
void
fileCreateEmpty(char* path) {
fclose(fopen(path, "w"));
}
file_t*
fileInit(char* path) {
file_t* f = malloc(sizeof(file_t));
@@ -80,6 +96,12 @@ fileInit(char* path) {
f->path = path;
if (fileExists(f) == 0) {
// if file 'f' does not exist
fileCreateEmpty(f->path);
return fileInit(f->path);
}
f->length = fileCountLines(f);
f->lines = vectorInit(VECTOR); // vector of vectors of chars = vector of strings
@@ -161,3 +183,42 @@ fileWrite(file_t* f, char* payload) {
f->length++;
f->not_newline_terminated = 1;
}
void
fileCopy(file_t* src, char* dst) {
FILE* fd = fopen(dst, "w");
if (!fd) {
fprintf(stderr, "could not open file for writing\n");
exit(EXIT_FAILURE);
}
char ch;
for (int i = 0; i < src->length; i++) {
for (int j = 0; j < ((vector_t *)vectorGetAt(src->lines, i))->size; j++) {
ch = *((char *)vectorGetAt((vector_t *)vectorGetAt(src->lines, i), j));
fprintf(fd, "%c", ch);
}
fprintf(fd, "\n");
}
fclose(fd);
}
void
fileDelete(file_t* f) {
int retval = remove(f->path); // try to remove/delete a file
if (retval != 0) { // if it could not do so, raise an error
fprintf(stderr, "could not delete file\n");
// fileCleanup(f); // don't know if this is necessary... :shrug:
// exit(EXIT_FAILURE);
}
fileCleanup(f);
}
void
fileMove(file_t* src, char* dst) {
fileCopy(src, dst);
fileDelete(src);
}