Page 1 of 3 123 LastLast
Results 1 to 10 of 23

Thread: C, fprintf with commas

  1. #1
    squakie is offline I Ubuntu, Therefore, I Am
    Join Date
    Oct 2012
    Beans
    2,238
    Distro
    Ubuntu 14.04 Trusty Tahr

    C, fprintf with commas

    I need to write a "record" to a file that is in this syntax"

    var1,var2,var3,var4

    I literally need the commas in the file.

    I've tried strcat with ",", but when I printf the resulting string for testing I get:

    var1var2var3var4

    I've tried fprintf with "%s%s%s%s%s%s%s\n" and var1, ",", var2, ",", var3, ",", var4, but then it's like there is a newline between each variable and no commas print:
    var1
    var2
    var3
    var4

    I'm not the sharpest knife in the drawer, and especilly when it comes to C. But surely there has to be a way for me to write to a file as:

    var1,var2,var3,var4 and newline

    I have no clue how to do it and could really use some help. I'm back to being a novice at this so try to be gentle

  2. #2
    Join Date
    Aug 2011
    Location
    47°9′S 126°43W
    Beans
    2,165
    Distro
    Kubuntu 14.04 Trusty Tahr

    Re: C, fprintf with commas

    And

    Code:
    fprintf(file,"%s,%s,%s,%s\n",var1,var2,var3,var4)
    Doesn't work (assuming your variables are strings)?
    Warning: unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.

  3. #3
    squakie is offline I Ubuntu, Therefore, I Am
    Join Date
    Oct 2012
    Beans
    2,238
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: C, fprintf with commas

    the variables are string arrays, if that makes any difference. If I want to trim traling spaces, how do I do the compare of var[x] to space? I've tried ' ' and decrement "x" but it seems to go forever until I get a segment overflow ("x" has gone to a large negative number).

    I *used* to know C - that was over 20 years ago. I don't know squat now, so I'm really starting over completely from scratch.

    Thanks!

  4. #4

    Re: C, fprintf with commas

    In that case it might be good to post the actual code you're working on. It's hard to say what you might be doing wrong otherwise, since both strcat and fprintf will work if used correctly.

    Here's a snippet that will chop off the end of a string starting at the first space -- i.e. it transforms "hello, world " into "hello,". I'm lazy, so I won't do the whole "go to the end of the string, then go back to the last space following a non-space" algorithm to do space-trimming the right way, but it's a start:
    Code:
    str s[] = "hello, world ";
    int i = 0;
    //puts(s);
    while (s[i] != ' ') {
        i++;
    }
    s[i] = '\0';
    //puts(s);
    And for good measure, here's an oddly specific function borrowed from Perl that removes the last character (and only the last) from a string only if that character is a newline. It often comes in handy when using fgets(), but I post it here just for illustrative purposes -- it uses both pointer arithmetic and indexing. I'm not sure what I should try to explain about this code, but if you post questions I'll try to answer them when I can. Hope it helps.
    Code:
    int chomp(char *s)
    {
        if (s == NULL || *s == '\0') {
            /* this is here to prevent bad stuff if someone calls chomp("") or chomp(NULL) */
            return 0;
        }
        while (*s) {
            s++;
        }
        if (s[-1] == '\n') {
            s[-1] = '\0';
            return 1;
        }
        return 0;
    }

  5. #5
    squakie is offline I Ubuntu, Therefore, I Am
    Join Date
    Oct 2012
    Beans
    2,238
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: C, fprintf with commas

    given:

    Code:
    wrk_string1 = csv_last_name;
       strcat(wrk_string1,  "    ");
       strcat(wrk_string1, csv_first_name);
    
       fprintf(outfile,"%s,%s,%s,%s\n",wrk_string1,csv_last_name, csv_first_name, csv_email );
    I get:

    Code:
    lname    fname
    ,lname    fname
    ,lname
    ,fname
    ,email
    I should be getting:

    Code:
    lname    fname,lname,fname,email
    I use functions pretty much the same as this to load the variables:
    Code:
    oid type_Name()
    {
    
       memset(csv_name, '\0', my_size);
       memset(csv_last_name, '\0', my_size);
       memset(csv_first_name, '\0', my_size);
       ++wrk1;
       wrk2 = strlen(my_input_string);
       wrk3 = wrk2 - wrk1;
       if ( wrk3 > 0)
          {
              memcpy(csv_name, my_input_string + wrk1, wrk3);
              wrk1 = strcspn(csv_name, ",");
              wrk2 = strlen(csv_name);
              memcpy(csv_last_name, csv_name, wrk1);
              wrk3 = wrk2 - wrk1;
              if ( wrk3 > 2)
                {
                    wrk1 = wrk1 + 2;
                    memcpy(csv_first_name,csv_name + wrk1, wrk3);
                }
          }
    wrk1 = strlen(csv_last_name);
    wrk2 = strlen(csv_first_name);
    printf("lname length: %d, fname length: %d\n",wrk1, wrk2);
    
    
    }
    where the variables are defined as:
    Code:
    char csv_email[my_size];
    char csv_alias[my_size];
    char csv_name[my_size];
    char csv_last_name[my_size];
    char csv_first_name[my_size];
    char csv_primary_phone[my_size];
    char csv_address[my_size];
    char csv_birth[my_size];
    char csv_deleted[my_size];
    When I look at the output file in gedit and click beyond the last character in a line it goes back to right after the last character, so there are no trailing spaces that I can tell.

    Sorry this is so long, but if I can get this part working I'll be able to convert my brother in-law's Juno address book to a comma sepearate values file I can then use to import the converted address book to another email program.

    Thanks for your patience, and thanks for understanding I'm just very green on this now.

  6. #6
    squakie is offline I Ubuntu, Therefore, I Am
    Join Date
    Oct 2012
    Beans
    2,238
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: C, fprintf with commas

    BTW - thanks so much for the help. I'm head off to bed now as I've been up all night trying to figure this out, and it's now 7:30 a.m. and I need to get at least a little sleep

  7. #7

    Re: C, fprintf with commas

    (Are you sure that output comes from that code? The code prints 3 commas, the output has 4. If that's right, it means your data has commas in it.)

    I'm a bit occupied today as well, so I can't give it my full attention, but it looks like at least some of your strings have newlines in them. Maybe that chomp() function I wrote up above could be useful to you after all. Try putting calls to chomp(csv_whatever) at the bottom of type_Name(), before you do any processing, and see how it affects the output.

    Declarations and initialization code for wrk1, wrk2, wrk3 and my_input_string would be helpful as well.

    Ok, now one thing you should realize about this code:
    Code:
       wrk_string1 = csv_last_name;
       strcat(wrk_string1,  "    ");
       strcat(wrk_string1, csv_first_name);
    is that the assignment doesn't copy the string; it merely copies a pointer to its first character. (I'm assuming wrk_string1 is of type char *, because that's the only thing that makes sense here.) After the first line, wrk_string1 and csv_last_name refer to the same string, and strcat() doesn't know the difference, so you change both at once. If you printf("csv_last_name: <%s>\n", csv_last_name) after this point, you'll see csv_last_name now contains csv_first_name as well.

    To avoid this, you can allocate a new buffer and strcpy the old string into it, but I'd instead use sprintf in a manner similar to the following:
    Code:
    char wrk_string1[1500]; /* make it big, it ain't 1990 anymore */
    sprintf(wrk_string1, "%s    %s", csv_last_name, csv_first_name);
    (Actually, I would use snprintf for safety, but that's ok, this is a one-off, right?)

    In fact, if that's all you're doing to generate wrk_string1, just wrap it into your fprintf string:
    Code:
    fprintf(outfile, "%s    %s,%s,%s,%s\n", csv_last_name, csv_first_name, csv_last_name, csv_first_name, csv_email);

  8. #8
    Join Date
    Aug 2011
    Location
    47°9′S 126°43W
    Beans
    2,165
    Distro
    Kubuntu 14.04 Trusty Tahr

    Re: C, fprintf with commas

    Quote Originally Posted by squakie View Post
    given:

    Code:
    wrk_string1 = csv_last_name;
       strcat(wrk_string1,  "    ");
       strcat(wrk_string1, csv_first_name);
    
       fprintf(outfile,"%s,%s,%s,%s\n",wrk_string1,csv_last_name, csv_first_name, csv_email );
    I get:

    Code:
    lname    fname
    ,lname    fname
    ,lname
    ,fname
    ,email
    I should be getting:

    Code:
    lname    fname,lname,fname,email
    If you get this, it means you have remaining linefeeds in your data...
    Warning: unless noted otherwise, code in my posts should be understood as "coding suggestions", and its use may require more neurones than the two necessary for Ctrl-C/Ctrl-V.

  9. #9
    squakie is offline I Ubuntu, Therefore, I Am
    Join Date
    Oct 2012
    Beans
    2,238
    Distro
    Ubuntu 14.04 Trusty Tahr

    Re: C, fprintf with commas

    Well, I tried creating just a test file for input via gedit so I know where everything terminates:
    Code:
    Type:Entry 
    Email:myemal@mine.com 
    Alias: 
    Name:last name   first name 
    Primary Phone:my phone 
    Birth:my birth 
    Address:my address 
    Deleted:0 
    Time:1300446059
    and that's a copy/paste from the editor.

    I ran the program with a printf to echo what it's picking up and generating for the name:
    Code:
    /**************************************************
    *   Process "Name:"
    **************************************************/
    
    void type_Name()
    {
    
       memset(csv_name, '\0', my_size);
       memset(csv_last_name, '\0', my_size);
       memset(csv_first_name, '\0', my_size);
       ++wrk1;
       wrk2 = strlen(my_input_string);
       wrk3 = wrk2 - wrk1;
    printf("\nat name, %s, start: %d, length: %d, num to copy: %d\n\n",my_input_string, wrk1, wrk2, wrk3);
       if ( wrk3 > 0)
          {
              memcpy(csv_name, my_input_string + wrk1, wrk3);
              wrk1 = strcspn(csv_name, ",");
              wrk2 = strlen(csv_name);
              memcpy(csv_last_name, csv_name, wrk1);
              wrk3 = wrk2 - wrk1;
              if ( wrk3 > 2)
                {
                    wrk1 = wrk1 + 2;
                    memcpy(csv_first_name,csv_name + wrk1, wrk3);
                }
          }
    
    
    }
    This is the output from the printf:
    Code:
    at name, Name:last name   first name
    , start: 5, length: 29, num to copy: 24
    Note how right there the name string is goofed all ready - there shouldn't be a newline after "first name". The length of the entire string (29, the value of wrk2 in the code) is correct. Where I want to start (5, the value of wrk1 in the code) is correct. The number of characters I want to move (24, wrk3 in the code) is correct. It is starting at 5 since the input line that gets to here is:
    Code:
    Name:last name   first name
    . I parse until the first ":" to know the statement it found, then execute the code based on that string, in this case "Name:". Coming into the name function, wrk1 is at 4, indicating where it found the ":", so it is incremented to get past the ":".

    I don't know if that helps or not. I've got to be doing something extremely stupid wrong, but I just don't know.

    If you would prefer I not ask this in the forum (perhaps it's meant for people who actually know what they are doing first ) just let me know.

    Thanks again SO much!





    This is the output file:
    Code:
    Name,EmailAddress,FirstName,LastName
    last name   first name 
        ,myemal@mine.com 
    ,
    And finally, the output was generated by this code, which I had commented out while testing the fprintf as per above:
    Code:
    /************************************************
    *   Create CSV entry    
    ************************************************/
    
    void create_CSV()
    {
    
    /*  Format:  Name,EmailAddress,FirstName,LastName  */
    
    
       wrk1 = 0;
       wrk2 = strlen(csv_last_name);
       while( wrk1 < wrk2)
          {
             fputc(csv_last_name[wrk1],outfile);
             ++wrk1;
          }
       wrk1 = 0;
       while (wrk1 < 4)
          {
             fputc(' ',outfile);
             ++wrk1;
          }
       wrk1 = 0;
       wrk2 = strlen(csv_first_name);
       while (wrk1 < wrk2)
          {
             fputc(csv_first_name[wrk1], outfile);
             ++wrk1;
          }
       fputc(',',outfile);
    
       wrk1 = 0;
       wrk2 = strlen(csv_email);
       while (wrk1 < wrk2)
          {
             fputc(csv_email[wrk1], outfile);
             ++wrk1;
          }
       fputc(',',outfile);    
    
    
    }

    EDIT: I just noticed, by doing some more testing, that all of the generated strings appear to be having the same problem, as can be witnessed by the email address, an apparently long string so it does a newline, followed by it's terminating comma. Perhaps I'm doing something wrong with the memcpy statements? My understanding was that it would only copy the number of characters (wrk3 in the code) from the input string to the output string. Since I memset each output string to all '\0' before doing the memcpy, I assumed i would end up with a string output after the memcpy - if memcpy just copies that number of character the "preloaded" '\0' should terminate the output right after the number of characters are moved. Least wise I hope so. There can't be any extra newlines in the input as I created it right in gedit.
    Last edited by squakie; February 28th, 2014 at 11:06 PM.

  10. #10
    Join Date
    Apr 2012
    Beans
    6,947

    Re: C, fprintf with commas

    What exactly are you trying to do? If you are just wanting to read and tokenize lines of input based on a colon separator your code seems unnecessarily obfuscated. Or am I misunderstanding the point of the exercise?

Page 1 of 3 123 LastLast

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •