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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With