I'm having an issue with fseek and fread. For some reason, using fseek (f, 0, SEEK_END);
will not give me the end of my file, and instead go 1000 bytes farther, giving me junk data and generally being a pain...
I have checked, if I open the same file with python, f=open("filename","r"); print(len(f.read()))
will give me the correct result, but using ftell()
in C after the line I wrote previously will be 1000 off, and I have no idea why.
Here is the entire code for the function that is not working:
char* get_input(const char* path) {
char* buffer = NULL;
FILE* f = fopen(path, "r");
if (f)
{
fseek (f, 0, SEEK_END);
const long length = ftell(f);
fseek (f, 0, SEEK_SET);
printf("%d\n", length);
buffer = malloc(length+1);
if (buffer)
{
fread (buffer, 1, length, f);
buffer[length+1] = '\0';
}
fclose (f);
}
return buffer;
}
(it's just trying to read the contents of the file as a char array...) The file I'm trying to open is just my day 2 input from advent of code(2024), that I copy-pasted to a text file as usual. I will not share it unless necessary as it is not good practice to do so.
With the help of the comments, I have found the two issues: The first one was: I read my file as text when I should have read it as binary. The second one was: I did not place my null terminator correctly.
The code I ended up using is:
char* get_input(const char* path) {
char* buffer = NULL;
FILE* f = fopen(path, "rb");
if (f)
{
fseek (f, 0, SEEK_END);
const long length = ftell(f);
fseek (f, 0, SEEK_SET);
buffer = malloc(length+1);
if (buffer)
{
size_t bytes = fread (buffer, 1, length, f);
buffer[bytes] = '\0';
}
fclose (f);
}
return buffer;
}