Fgetc zero limiter

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?

+4
source share
4 answers

Yes, you're lucky. To avoid this problem, you could use fwrite , which does not require a null terminator (since you determine exactly how many bytes to write):

 fwrite(buffer, 1, n, stdout); 
+5
source

You can specify printf(...) maximum number of characters to print for a given string.

 printf("%.*s\n", n, buffer); 

See printf (3) , the Precision section:

Optional precision in the form of a period ('.') Followed by an optional decimal digit. Instead of a decimal digit string, you can write "*", [...] indicate that the precision is indicated in the next argument [...], which must be of type int. [...] This gives the maximum [...] number of characters to print with string for s [...] conversions.

Live demo of printf ("%.*s\n", 5, "Hello, world!") : Http://ideone.com/KHKLl .

+4
source

You can initialize your buffer:

 memset(buffer, '\0', MAX_LENGTH + 1); 

And you don't have to worry about zero termination.

+2
source

As the other answers pointed out, you are lucky that the array contains zeros in the right places.

You can initialize it when you create it using this shortcut:

 char buffer[MAX_LENGTH + 1] = { 0 }; // all elements will be zero 

Note that this is because the compiler will initialize unspecified entries with zeros - so if you said

 char buffer[MAX_LENGTH + 1] = { 'a' }; 

then the array will be {'a',0,0,0....}

+1
source

Source: https://habr.com/ru/post/1389386/


All Articles