Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgetc null terminator

I'm doing an exercise in K&R:

Write a program detab that replaces tabs in the input with the proper number of blanks to space to the next tab stop.

And this is what I have so far (w/o error checking on the file):

#include <stdio.h>
#define tab 2
#define MAX_LENGTH 1000
int main(int argc, char **argv)
{
    FILE *fp = fopen(argv[1], "r+");    
    int c, n;
    char buffer[MAX_LENGTH + 1];
    for (n = 0; n < MAX_LENGTH && (c = fgetc(fp)) != EOF; ++n) {
        if (c == '\t') {
            for (int x = 0; x < tab; ++x)
                buffer[n++] = ' ';
            --n;
        }
        else
            buffer[n] = c;
    }
    //buffer[n] = '\0';
    //rewind(fp);
    //fputs(buffer, fp);
    printf("%s\n", buffer);
    fclose(fp);
    return 0;
}

It seems to work, but I'm wondering why \0 wasn't needed at the end. Was I just lucky?

like image 699
mwlow Avatar asked Dec 17 '22 05:12

mwlow


1 Answers

Yes, you were lucky. To avoid this problem, you could have used fwrite, which doesn't require a null terminator (since you specify exactly how many bytes to write):

fwrite(buffer, 1, n, stdout);
like image 81
Greg Hewgill Avatar answered Dec 26 '22 21:12

Greg Hewgill