The "garbage" comes from improperly examining/printing archivo
and code not noting how much was read.
fread()
saves into archivo
data, but that data is not certainly null character terminated - a C string. Append a '\0'
if archivo
is to point to a string.
But where? After the last character read - which is determined by the return value of fread()
, not after the number of characters requested.
Even without an error, the return value may be less than the number of requested characters due to text mode end-of-line translation of "\r\n"
into "\n"
. The value returned from ftell()
is not necessarily the numbers of characters that will be read in text mode.
No need to attempt to read tamanioArchivo+1
characters. Use tamanioArchivo
.
Also see @ Andrew Henle good comment about fread(ptr, element_size, number_of_elements, stream)
parameter order.
// Note that the file is opened in text mode, not binary mode
FILE *fp = fopen (path, "r");
fseek(fp, 0, SEEK_END);
// int tamanioArchivo = sizeof(char) * ftell(fp);
long tamanioArchivo = ftell(fp);
fseek(fp, 0, SEEK_SET); // or `rewind(fp);
// Good to allocate +1 for the null chracter
char* archivo = malloc(tamanioArchivo + 1u);
// Save the return value and drop the +1
// fread(archivo, tamanioArchivo+1, 1, fp);
size_t read_count = fread(archivo, 1, tamanioArchivo, fp);
// bad
// bytes read may be less than the offset due to CR/LF-->LF or input error
archivo[tamanioArchivo] = '\0';
// good
archivo[read_count] = '\0';
//do something with archivo
puts(archivo);
fclose (fp);
free(archivo);
Robust code would check the return value of fopen()
, malloc()
, fseek()
, ftell()
for unusual return values. The seek to the end, ftell()
method for determining file length has additional limitations. Alternatives depend on various unposted coding goals.