How to print a string of the first n bytes when the string is longer than n?

So, I have a string with a certain number of bytes (or lengths). I say bytes because there is no NULL terminator at the end of the line. Although, I know how long the string. Usually, as we all know, when you printf("%s", str); , it will print every byte until it reaches the NULL character. I know that there is no C line that is not NULL terminated, but I have a strange situation where I am storing material (not specifically strings) and I am not storing NULL, but the length is β€œthing”.

Here is a small example:

 char* str = "Hello_World"; //Let use our imagination and pretend this doesn't have a NULL terminator after the 'd' in World long len = 5; //Print the first 'len' bytes (or char's) of 'str' 

I know that you are allowed to do something like this:

 printf("%.5s", str); 

But in this situation, I hardcode 5, although in my situation 5 is in a variable. I would do something like this:

 printf("%.(%l)s", len, str); 

But I know that you cannot do this. But it gives you an idea of ​​what I'm trying to accomplish.

+6
source share
3 answers

printf("%.*s", len, str);

and also there is no C line that is not NULL terminated.

+21
source

You can do it:

 for (int i =0; i<len; i++) { printf("%c", str[i]); } 

That will print them in one line, looping for any length that you want to print.

+1
source

You can detect zero byte poisoning like this. Program display showing detected Null Byte

  char filename[] = "path/image.php\0.bmp"; if ((sizeof(filename) - 1) == strlen(filename)) { printf("%s %s", "No poisoning Null Byte detected" , "\n"); FILE *fp; fp = fopen(filename, "r"); if ( fp == NULL ) { perror ( "Unable to open the file" ); exit ( 1 ); } fread ( buf, 1, sizeof buf, fp ); printf ( "%s\n", buf ); fclose ( fp ); } else { printf("%s %s", "Poisoning Null Byte detected" , "\n"); } 
0
source

All Articles