Thread: Help rewrite from C++ (avoid using ostringstream)

  1. #1
    Registered User
    Join Date
    Feb 2011
    Posts
    9

    Help rewrite from C++ (avoid using ostringstream)

    Hello,

    I was given a task to modify our C application a little. I need to add a feature to log messages, with the file name being the same as a messageId (which comes as 24-byte array).

    In another C++ application, the routine looks like this:

    Code:
    bool saveMessage(const string& path, const MQMD& md, const MQLONG len)
    {
      bool res = false;
      ostringstream msgId;
      unsigned char *pch;
      string messageFileName;
      ofstream fout;
      int i;
      
      msgId.fill('0');
      msgId << hex;
      pch = (unsigned char *)md.MsgId;
      for (i = 0; i < sizeof(md.MsgId); i++)
        msgId << setw(2) << (int)pch[i];
    
      messageFileName = path + "/" + msgId.str() + ".msg";
      // and now I can use messageFileName to whatever I want
    }
    I need to achieve the same functionality in plain C, but am strugling. I tried looping through the md.msgId a copying it byte by byte to unsigned char array, but to no avail.

    Any help appreciated, thanx!

  2. #2
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Let's see what code you have so far in C, so we can help you find your problems. Also, you should take a look at our File I/O tutorial and Google around for some more tutorials and examples. Of couse you'll need to open and close the file using fopen and fclose. For writing to the file, you can write text (like you would write to the console) using fprintf, or you can write binary data using fwrite.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Need to start with the fact that you can't pass by reference in that way with C. You need to use pointers. And there are no strings in C either.

    anduril462 is right...show us what you've tried, don't expect us to do your work for you.

  4. #4
    Registered User
    Join Date
    Feb 2011
    Posts
    9
    Sure I don't expect you to do all my work...

    So far, I only got this far. And the output is just some unreadable characters.

    Code:
    int saveMessage(MQMD *md)
    {
      char fileName[1024];
      unsigned char *pch;
      int i;
    
      pch = (unsigned char *)malloc(sizeof(md->MsgId));
      memcpy(pch, md->MsgId, sizeof(md->MsgId));
      for (i = 0; i < sizeof(md->MsgId); i++)
      {
        pch[i] = (md->MsgId[i] & 0x0f);
      }
    
      for (i = 0; i < sizeof(md->MsgId); i++)
      {
        printf("%c", (char)pch[i]);
      }
      pch[++i] = '\0';
      printf("pch: %s\n", pch);
    
      // and here i would like to memcpy pch somewhere, build a complete path+filename and then work with the file as usual
    
      free(pch);
    }
    The next piece of code is what I took from an example that prints the MsgID in the way I need it, except it prints it to an output and not to a variable (what is what I need):
    Code:
        for(i=0;i<24;i++) printf("%1.1X",(md->MsgId[i] & 0x0f) );

  5. #5
    Registered User
    Join Date
    Nov 2010
    Location
    Long Beach, CA
    Posts
    5,909
    Did you read any tutorials on file I/O? I don't even see an attempt to open a file, let alone do anything with it. Not even a declaration of a file handle. Here are the docs for fopen/fclose, fread/fwrite, fprintf and fscanf.

    That last snippet of code doesn't "print to a variable". It prints to the standard output, which is your screen. You want the version that prints to a file, so look at the link for fprintf I gave you.

  6. #6
    Registered User
    Join Date
    Feb 2011
    Posts
    9
    I know how to open a file, declare a file handle etc.

    Maybe it was not clearly written in the first post, but my problem is not how to write to a file, my problem is to generate a filename into a variable. Then I will use this filename to open a file as usual.

    In the C++ piece of code, the stream was used to generate a file name, not to write in the file itself.

  7. #7
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    You can use sprintf/snprintf.
    Not sure what you really want. Tell us in plain English language. Not all of us here know C++. Well at least I don't know/care C++.

  8. #8
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Code:
    char fileName[PATH_MAX] = { 0 };
    int i = 0;
    while (i < 5) {
        sprintf(fileName, "file%d", i);
        printf("Filename for %d is %s\n", i, fileName);
        ++i;
    }
    Last edited by rags_to_riches; 03-21-2011 at 06:13 AM. Reason: Forgot an arg to printf

  9. #9
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Look up sprintf().

    %X as a format specifier prints an (unsigned) integer to the string as hex. %0X prints as hex, but replaces any spaces that would be output with a zero.

    Obviously you need to make sure you supply a character buffer large enough (no self-resizing buffers in C). Either the caller must supply the buffer, or your code must allocated it.

    To concatenate multiple strings, use strcpy() for the first string, and strcat() for subsequent ones. Similar caveats about buffers apply.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  10. #10
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    This may help:

    Code:
    #include <stdio.h>
    #include <string.h>
    #define SIZE 100
    
    int main() {
      int i;
      char filename[SIZE]="";
      char path[SIZE]="C:\\TC\\BIN\\"; //doubled backslashes required
      char ext[5]=".txt";              
      char s[SIZE]="";
      printf("\nEnter a base for the filenames: \n");
      fgets(filename, SIZE, stdin);
      i = strlen(filename);
      if(filename[i-1]=='\n')
        filename[i-1]='\0'; //remove the newline - essential
      
      for(i=0;i<20;i++) {
        strcat(s,path);
        strcat(s, filename);
        sprintf(s+strlen(s),"%d%s", i,ext);
        printf("filename: %s\n",s);
        s[0]='\0';  //reset for the next loop
      }
      printf("\n\n\t\t\t     press enter when ready");
      (void) getchar(); 
      return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Avoid duplicate input issue
    By Eyesight in forum C Programming
    Replies: 6
    Last Post: 12-03-2010, 10:58 AM
  2. Create a ostringstream like class.
    By ThLstN in forum C++ Programming
    Replies: 6
    Last Post: 09-06-2008, 08:43 PM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. How to avoid a flickring in XOR_PUT
    By planet_abhi in forum Game Programming
    Replies: 3
    Last Post: 10-02-2003, 02:49 PM
  5. ostringstream question
    By Swaine777 in forum C++ Programming
    Replies: 1
    Last Post: 07-10-2003, 06:43 PM