Reputation: 310
I'm running into an issue trying to make some functions to make FileIO in C easier, where \n is stored as two bytes on the computer, but is held in a single char. This results in the file loaded being slightly shorter than the real size, giving some extra junk on the end. I'm using chars as bytes because it's the only data type that holds a single byte. Here's my code:
#include <stdio.h>
#include <stdlib.h>
long getFileSize(char fileName[]) {
FILE* f;
long size;
f = fopen(fileName, "r");
fseek(f, 0L, SEEK_END);
size = ftell(f);
return size;
}
char* readFile(char fileName[]) {
FILE* f;
char* data;
long size;
f = fopen(fileName, "r");
size = getFileSize(fileName);
data = malloc(size);
fread(data, 1, size, f);
fclose(f);
return data;
}
char* writeFile(char fileName[], char* data, long length) {
FILE* f;
f = fopen(fileName, "w");
fwrite(data, 1, length, f);
fclose(f);
return data;
}
int main(void) {
char* data = readFile("test.txt");
long size = getFileSize("test.txt");
int i;
printf("%li\n", size);
for(i = 0; i < size; i++) {
printf("%c", *(data + i));
}
printf("\n");
writeFile("test.txt", data, size);
free(data);
return 0;
}
Upvotes: 0
Views: 48
Reputation: 310
The issue was me having used "w" and "r" instead of "wb" and "rb", as pointed out by @chux
fopen(fileName, "r"); --> fopen(fileName, "rb");
Oops.
Upvotes: 1