Thread: sprintf giving me issues

  1. #16
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    You can use "%02d" format

    or don't use sprintf at all

    Code:
    #include <string.h>
    #include <stdio.h>
    
    int main(int argc, char* argv[])
    {
    	char modelName [] = "modelB.xx";
    	int len = strlen(modelName);
    	char a;
    	char b;
    
    	for(a='0';a<= '9'; a++)
    	{
    	   for(b='0';b<='9';b+=5)
    	   {
    		  modelName[len-2] = a;
    		  modelName[len-1] = b;
    		  printf("%s\n",modelName);
    	   }
    	}
    	return 0;
    }
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  2. #17
    Registered User
    Join Date
    Nov 2006
    Posts
    176
    I re-read you post and may not really understand what you want your output to look like.

    show an example

    like 5 should be?
    modelname.05

    modelname.500?

    modelname.0500?

  3. #18
    Registered User
    Join Date
    Nov 2006
    Posts
    25
    Ah, works like a charm--thanks so much! Now, when I try to open the file, it doesn't quite work. I know I'm pointing to the right location because the file does open when, after all that code, I say modelfile=(string with the right file name), where that string is exactly the same as what I created (modelname.xx). Any idea what the problem is here? Code:
    Code:
    for (i = 0; i <= 90; i += 5) { //Loops through all inclinations.
             if (i < 10) {
                   sprintf(inc, "0%d", i);
             } else {
                    sprintf(inc, "%d", i);
             }
             modelfile = malloc(strlen(modelname) + strlen(inc) + strlen("Lightcurves\\") + 1);
             sprintf(modelfile, "%s%s%s%s", "Lightcurves\\", modelname, inc, ".mag");
             printf("%s\n", modelfile); //String 1
             modelfile="Lightcurves\\modelB.00.mag";
             printf("%s\n", modelfile); //String 2, appears exact same as String 1
             model = fopen(modelfile, mode); //This opens the file properly with String 2 but NOT when I use string 1.
    if (model == NULL) { //Error handling.
    fprintf(stderr, "Can't open input file!\n");
    system("pause");
    exit(1);
    } else {
    printf("File opened successfully.\n");
    }
    system("pause");
             free(modelfile);
         } //Ends loop.

  4. #19
    Registered User
    Join Date
    Nov 2006
    Posts
    25
    Erm, if I'm not being totally clear here, basically the issue is that when I create the string by adding together different bits, it doesn't find the file, but when I create the same string by typing it in manually, it does find the file. I would type them all in manually but that would be kind of unwieldy since I'd need to create an array of 19 similar strings ("Lightcurves\\modelB.00.mag", etc.).

  5. #20
    Registered User
    Join Date
    Nov 2006
    Posts
    176
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main (void) {
            int i;
            char *modelfile;
            char modelname[] = "modelname.";
            char inc[3];
            FILE *fp;
    
            modelfile = malloc(strlen(modelname) + 4);
    
            for (i = 0; i < 99; i += 5)
            {
                    if (i < 10)
                            sprintf(inc, "0%d", i);
                    else
                            sprintf(inc, "%d", i);
    
            sprintf(modelfile, "%s%s", modelname, inc);
            printf("%s\n", modelfile);
    
            if ((fp = fopen(modelfile, "w")) == NULL)
            {
                    perror("Crap");
                    exit(1);
            }
    
            fprintf(fp, "wrote to file");
    
            }
    
            fclose(fp);
            free(modelfile);
            return 0;
    }
    this wrote to the files fine for me
    each one had the "wrote to file message"

  6. #21
    Registered User
    Join Date
    Nov 2006
    Posts
    25
    Yes, but I'm trying to read files that already exist, not write to new ones. It's not finding the files when I build the string, but it is finding them when I type in the same string manually.

  7. #22
    Registered User
    Join Date
    Nov 2006
    Posts
    176
    should work, I just changed my fopen to open the files for reading....then used fgets, to read a line
    and it read each file fine.

    Code:
            if ((fp = fopen(modelfile, "r")) == NULL)
            {
                    perror("Crap");
                    exit(1);
            }
    
            fgets(data, 14, fp);
            printf("%s\n", data);
    should tidy up your code a bit so its easier to read...add some whitespace etc.

  8. #23
    Registered User
    Join Date
    Nov 2006
    Posts
    25
    OK, new development, so this always fails the first time through, but then on subsequent loops, it opens up the file just fine....

  9. #24
    Registered User
    Join Date
    Nov 2006
    Posts
    25
    OK! I've slightly (haha, slightly...) modifed my code. The good news is, it compiles and then opens up all the files! The bad news is, even though it compiles and runs, I get warnings when I compile. Here's the new code:

    Code:
    void fitCurves()
    {
         int i;
         char inc[3];
         char *modelfile[19][20];
         char *temp;
         out = fopen("bestinc.txt", "a+"); //Opens file to write results to.
         fprintf(out, "i\tX^2\n"); //Prints header in periods.txt.
         for (i = 0; i <= 90; i += 5) {
             sprintf(inc, "%02d", i);
             temp = malloc(strlen(modelname) + strlen(inc) + strlen("Lightcurves\\") + 1);
             sprintf(temp, "%s%s%s%s", "Lightcurves\\", modelname, inc, ".mag");
             strcpy(modelfile[i/5], temp);
             free(temp);
         }
         for (i = 0; i <= 90; i += 5) { //Loops through all inclinations.
             printf("%s\n", modelfile[i/5]);
             model = openFile(modelfile[i/5]);
             fclose(model);
         } //Ends loop.
    }
    Where openFile is a function I defined elsewhere to open the file and let me know if it was successful or not. So I changed my approach from doing everything at once to creating an array of strings, each with a different file name, so that in my second loop, I just open the appropriate file. The warnings I get are:

    70 C:\(personal)\EX5.c [Warning] passing arg 1 of `strcpy' from incompatible pointer type (for the strcopy)
    75 C:\(personal)\EX5.c [Warning] passing arg 1 of `openFile' from incompatible pointer type (for the model=openFile line)

    Any ideas why I'm getting these even though it compiles, and how to fix them without changing the functionality? Thanks!

  10. #25
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    Code:
         char *modelfile[19][20];
    remove *

    Code:
             temp = malloc(strlen(modelname) + strlen(inc) + strlen("Lightcurves\\") + 1);
             sprintf(temp, "%s%s%s%s", "Lightcurves\\", modelname, inc, ".mag");
    no place for ".mag" - memory overrun

    No checks for null pointers - you should check the values returned by the functions you call. They not always work as supposed, sometimes - errors occur
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  11. #26
    Registered User
    Join Date
    Nov 2006
    Posts
    25
    But I need the * so I can pass it to fopen()...when I remove the * from *modelfile I get a few problems, most importantly that it no longer opens the files. Also...which functions should I be checking null pointers for? Would that get rid of my warnings?

  12. #27
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    fopen awaits const char*
    in your case modelfile[i/5] has a type of char*[] == pointer to array of chars not a pointer to char.

    So no - you don't need a * to pass the modelfile[i/5] to the fopen function.

    which functions should I be checking null pointers for
    You are using not so many functions in your code, just read the manual about each one - the return value and possible errors part.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  13. #28
    Registered User
    Join Date
    Nov 2006
    Posts
    25
    Thanks so much! Sorry to keep asking questions but I'm not 100% sure how to fix this here...it crashes (at some point in the program) when I try declaring modelfile as either:

    char *modelfile[19];

    or

    char modelfile[19][20];

    So I really think my declaration is right. Is there a way to, just for the purposes of fopen, convert the char*[] to a char*? My main language is Java so this new way of handling strings (through chars) is still pretty strange to me...

  14. #29
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    So I really think my declaration is right.
    You wrong. The crash has other source - you do not use the memory in the right way. When you copy string - you do not check that there is enough memory for it.
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  15. #30
    Registered User
    Join Date
    Nov 2006
    Posts
    25
    OK...so how do I go about fixing this? Like I said, I'm fairly new to C, I'm not sure how it all works yet...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Sprintf overflows my buffer -- why?
    By Lasston in forum C Programming
    Replies: 26
    Last Post: 06-20-2008, 04:33 PM
  2. sprintf of float giving "1.#QO"
    By Mafepero in forum C++ Programming
    Replies: 2
    Last Post: 03-03-2008, 04:52 AM
  3. sprintf : garbage appended
    By yeller in forum C Programming
    Replies: 9
    Last Post: 12-17-2007, 10:21 AM
  4. sprintf() giving crash to program!!
    By maven in forum C Programming
    Replies: 4
    Last Post: 01-01-2006, 12:26 PM
  5. Sprintf
    By Trauts in forum C++ Programming
    Replies: 10
    Last Post: 01-15-2003, 01:35 PM