Decomposition is not your biggest problem here. Rather careless error checking, the use of old overweighted fscanf()
and fprintf()
and global variables are. Furthermore, the lack of const correctness in the input filenames, the overly long and verbose variable names and your unawareness of the +=
and ++
operators are just the bonus. I suppose that's why your code looks like it's bloated (and it is, in fact).
I'd rewrite the function like this:
void detab(const char *in, const char *out, int tabstop)
{
FILE *inf = fopen(in, "r");
if (!inf) return;
FILE *outf = fopen(out, "w");
if (!outf) {
fclose(inf);
return;
}
int n = 0;
int c;
while ((c = fgetc(inf)) != EOF) {
if (c == '\t') {
int pad = tabstop - n % tabstop;
for (int i = 0; i < pad; i++)
fputc(' ', outf);
n += pad;
} else if (c == '\n') {
fputc('\n', outf);
n = 0;
} else {
fputc(c, outf);
n++;
}
}
fclose(inf);
fclose(outf);
}
If you want to decompose this even further, then you may write a function taking two FILE *
and the tab stop as its arguments and it shall contain the while
loop only - doing that is left to you as an exercise.