Concat wchar_t Unicode strings in C?

Posted by Doori Bar on Stack Overflow See other posts from Stack Overflow or by Doori Bar
Published on 2010-05-05T00:14:22Z Indexed on 2010/05/05 0:18 UTC
Read the original article Hit count: 447

Filed under:

I'm a beginner, I play with FindFirstFileW() of the winapi - C. The unicoded path is: " \\?\c:\Français\", and I would like to concat "*" to this path of type wchar_t (then I will use it as an arg for FindFirstFileW()).

I made two test cases of mine, the first is ansi_string() which seem to work fine, the second is unicode_string() - which I don't quite understand how should I concat the additional "*" char to the unicoded path. I write the strings to a file, because I'm not able to print Unicoded characters to stdout.

Note: my goal is to learn, which means I'll appreciate guidance and references to the appropriate resources regards my scenario, I'm very much a beginner and this is my first attempt with Unicode.

Thanks, Doori Bar

#include <stdio.h>
#include <stdlib.h>
#include <wchar.h>
#include <string.h>
#include <errno.h>

void *error_malloc(int size);

void ansi_string(char **str1, char **str2);

void unicode_string(wchar_t **wstr1, wchar_t **wstr2);

void unicode_string(wchar_t **wstr1, wchar_t **wstr2)
{
  /* assign wstr1 with the path: \\?\c:\Français\ */
  *wstr1 = error_malloc((wcslen(L"\\\\?\\c:\\Français\\")+1) *sizeof(**wstr1));
  wcscpy(*wstr1,L"\\\\?\\c:\\Français\\");

  /* concat wstr1+"*" , assign wstr2 with: \\?\c:\Français\* */
  *wstr2 = error_malloc((wcslen(*wstr1) + 1 + 1) * sizeof(**wstr1));
  /* swprintf(*wstr2,"%ls*",*wstr1); */
  /* how should I concat wstr1+"*"? */
   wcscpy(*wstr2,L"\\\\?\\c:\\Français\\");
}

void ansi_string(char **str1, char **str2)
{
  /* assign str1 with the path: c:\English\ */
  *str1 = error_malloc(strlen("c:\\English\\") + 1);
  strcpy(*str1,"c:\\English\\");

  /* concat str1+"*" , assign str2 with: c:\English\* */
  *str2 = error_malloc(strlen(*str1) + 1 + 1);
  sprintf(*str2,"%s*",*str1);
}

void *error_malloc(int size)
{
  void *ptr;
  int errornumber;
  if ((ptr = malloc(size)) == NULL) {
    errornumber = errno;
    fprintf(stderr,"Error: malloc(): %d; Error Message: %s;\n",
            errornumber,strerror(errornumber));
    exit(1);
  }
  return ptr;
}

int main(void)
{
  FILE *outfile;
  char *str1;
  char *str2;
  wchar_t *wstr1;
  wchar_t *wstr2;

  if ((outfile = fopen("out.bin","w")) == NULL) {
    printf("Error: fopen failed.");
    return 1;
  }

  ansi_string(&str1,&str2);
  fwrite(str2, sizeof(*str2), strlen(str2), outfile);
  printf("strlen: %d\n",strlen(str2));
  printf("sizeof: %d\n",sizeof(*str2));
  free(str1);
  free(str2);

  unicode_string(&wstr1,&wstr2);
  fwrite(wstr2, sizeof(*wstr2), wcslen(wstr2), outfile);
  printf("wcslen: %d\n",wcslen(wstr2));
  printf("sizeof: %d\n",sizeof(*wstr2));
  free(wstr1);
  free(wstr2);

  fclose(outfile);
  return 0;
}

© Stack Overflow or respective owner

Related posts about c