I am doing an exercise in K & R:
Write a detab program that replaces the input tabs with the appropriate number of spaces until the next tab stops.
And this is what I have so far (without checking for errors in 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; }
This seems to work, but I wonder why \0 not needed at the end. I was just lucky?
source share