I'm learning C, I'm trying to read the contents of a file; I do not understand why the function does not fill the string of characters and reads 0
bytes. However, I think I read the manuals.
char *read_file(const char *filename)
{
int file;
int nb;
off_t size;
char *buffer;
file = open(filename, O_RDONLY);
if (file < 0)
return (NULL);
size = lseek(file, 0, SEEK_END);
buffer = (char*)malloc(sizeof(char) * (size + 1));
if (buffer == NULL)
return (NULL);
if ((nb = read(file, buffer, size)) < 0)
return (NULL);
close(file);
buffer[size] = '\0';
return (buffer);
}