concatenate char array in C

后端 未结 7 1670
故里飘歌
故里飘歌 2020-12-05 02:15

I have a a char array:

char* name = \"hello\";

I want to add an extension to that name to make it

hello.txt
7条回答
  •  [愿得一人]
    2020-12-05 02:36

    #include 
    #include 
    #include 
    
    char *name = "hello";
    
    int main(void) {
      char *ext = ".txt";
      int len   = strlen(name) + strlen(ext) + 1;
      char *n2  = malloc(len);
      char *n2a = malloc(len);
    
      if (n2 == NULL || n2a == NULL)
        abort();
    
      strlcpy(n2, name, len);
      strlcat(n2, ext, len);
      printf("%s\n", n2);
    
      /* or for conforming C99 ...  */
      strncpy(n2a, name, len);
      strncat(n2a, ext, len - strlen(n2a));
      printf("%s\n", n2a);
    
      return 0; // this exits, otherwise free n2 && n2a
    }
    

提交回复
热议问题