C语言 当字符串的长度大于 n 时,如何打印字符串的前 n 个字节?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15376765/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:40:34  来源:igfitidea点击:

How to print string first n bytes when the string's length is greater than n?

cstringbyteprintf

提问by Rob Avery IV

So I have a string that has a certain amount of bytes (or length). I say bytes because there is no NULL terminator at the end of the string. Though, I know how long the string is. Normally, as we all know, when you printf("%s", str);, it will keep printing every byte until it gets to a NULL character. I know there is no C string that is not NULL terminated, but I have a weird situation where I'm storing stuff (Not specifically strings) and I don't store the NULL, but the length of the "thing".

所以我有一个字符串,它有一定数量的字节(或长度)。我说字节是因为字符串末尾没有 NULL 终止符。不过,我知道字符串有多长。通常,众所周知,当您使用 时printf("%s", str);,它将继续打印每个字节,直到达到 NULL 字符为止。我知道没有不是 NULL 终止的 C 字符串,但是我有一个奇怪的情况,我正在存储东西(不是特别是字符串)并且我不存储 NULL,而是“事物”的长度。

Here is a little sample:

这是一个小示例:

char* str = "Hello_World"; //Let's 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 you are allowed to do something like this:

我知道你可以做这样的事情:

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

But with that situation, I'm hard coding the 5 in, though with my situation, the 5 is in a variable. I would do something like this:

但是在这种情况下,我很难对 5 进行编码,尽管在我的情况下,5 是一个变量。我会做这样的事情:

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

But I know you can't do that. But gives you an idea of what I'm trying to accomplish.

但我知道你不能那样做。但是让您了解我正在努力完成的工作。

回答by Aniket Inge

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

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

and also, there is no C string that is not NULL terminated.

而且,没有非 NULL 终止的 C 字符串。

回答by RobertoNovelo

You can do this:

你可以这样做:

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

Which will print them in the same line, looping for whatever lenght you need to print.

这将在同一行中打印它们,循环打印您需要打印的任何长度。

回答by Raymond Nijland

You could detect null byte poisoning like this. Program wil display Poisoning Null Byte detected

您可以像这样检测空字节中毒。程序将显示检测到中毒空字节

  char filename[] = "path/image.php##代码##.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");
  }