So im trying to read an entire text file using this function:
FILE *fp = fopen(path, "r");
fseek(fp, 0, SEEK_END);
int tamanioArchivo = sizeof(char) * ftell(fp);
fseek(fp, 0, SEEK_SET);
char* archivo = malloc(tamanioArchivo + 1);
fread(archivo, tamanioArchivo + 1, 1, fp);
//do something with archivo
fclose(fp);
free(archivo);
I debugged it and the problem seems to be on the fread line. It brings back the file and adds some garbage at the end. Any ideas what im doing wrong?
Generally C doesn't care what the contents of a file are. Whether it's text or binary data, it's read the same way. Meaning if you want to read a string and get something nicely null-terminated, you need to handle that yourself.
fread(archivo, tamanioArchivo+1, 1, fp);
This reads one extra byte (again, null-termination is a C thing, the file system does not enforce this). Get rid of the plus 1. Then you must ensure that it's null-terminated:
archivo[tamanioArchivo] = '\0';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With