Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Reading entire file come with garbage at the end [closed]

Tags:

c

file

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?

like image 722
Marco Avatar asked Oct 27 '25 21:10

Marco


1 Answers

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';
like image 152
Max Avatar answered Oct 29 '25 11:10

Max