0

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);
}
Student
  • 805
  • 1
  • 8
  • 11
ken
  • 127
  • 3
  • 8
  • 3
    When you call `lseek`, you are moving your read pointer to the end of the file. There's nothing to read after that point. You need to reset your read pointer to 0. Another advice: this approach is fine if the file is small enough to fit in memory, a better approach would be to read fixed number of bytes from the file, do your processing and loop. – lakshayg Jul 29 '18 at 16:54
  • like `rewind(file)` – Jean-François Fabre Jul 29 '18 at 16:55
  • 1
    @Jean-FrançoisFabre OP is using the POSIX interface of `open` and not `fopen`. – Ajay Brahmakshatriya Jul 29 '18 at 18:02
  • my bad. Changed duplicate link to match this – Jean-François Fabre Jul 29 '18 at 19:58
  • Why are you doing the `lseek`? Opening a file starts at the beginning by default. `SEEK_END` goes to the end of file. Read the manual for `lseek` again carefully. – lurker Jul 30 '18 at 11:15

0 Answers0