Home > OS >  When Reading a file (system call), Why do I set buf to '\0'?
When Reading a file (system call), Why do I set buf to '\0'?

Time:08-24

I want to know why when we're reading a file do we have set the buf equal to '\0' before we can close fd? I'll demonstrate in an example.

ssize_t read_textfile(const char *filename, size_t letters)
{
    int fd;
    int i, y;
    char *buf;
    if (!filename)
        return (0);
    fd = open(filename, O_RDONLY);
    if (fd < 0)
        return (0);
    buf = malloc(sizeof(char) * letters);
    if (!buf)
        return (0);
    i = read(fd, buf, letters);
    if (i < 0)
    {
        free(buf);
        return (0);
    }
    buf[i] = '\0';        // This is what I'm talking about
    close(fd);
    y = write(STDOUT_FILENO, buf, i);
    if (y < 0)
    {
        free(buf);
        return (0);
    }
    free(buf);
    return (y);
}

CodePudding user response:

I don't know why you think it's necessary, but assuming the read() reads all letters (i == letters), buf[i] = '\0' overruns your buffer. And your input file is left open if the malloc() fails.

CodePudding user response:

You do not have to and you do not need it in this code.,

This line makes a C string (adding null terminating character). As you use write you do not need it, but if you use any function taking string as a parameter you will need it.

CodePudding user response:

Given that the only use of buf after the "termination" is the write call and that writes buf[0] to buf[i-1], then the character at buf[i] is ignored. As such the "termination" serves no purpose at all.

Not only does it serve no purpose, it is in fact also a bug. If the file contains at least letters bytes, then i == letters and buf[i] will be out of bounds.

  • Related