Search code examples
cprintfargvformat-string

How to use Printf like format string with argv


I'm trying to add support to my program for something that would allow me to enter /Input/Images/%03d.png /Output/Images/%03d.blah, but I'm not sure how to do that?

I've googled around for every combination of format string, printf, and argv that I can think of.

I want to e able to load everything before the %03d as a constant, and loop over %03d to select multiple different input files, in order, to read them in. so it would be /Input/Images/000.png, then /Input/Images/001.png all the way to /Input/Images/999.png.

tl;dr I want to handle a sequence of files, but I don't know how to do that.


Solution

  • You could do it like this. The solution leaves much to be desired in string size checking, but the basis is this.

    You enter the paths and the file number base and and the number of files in the batch you want to process.

    #include <stdio.h>
    
    int main (int argc, char *argv[])
    {
        unsigned basenum, numfiles, i;
        char inname[1000], outname[1000];
    
        if (argc < 5)
            return 1;
        sscanf(argv[3], "%u", &basenum);
        sscanf(argv[4], "%u", &numfiles);
        for (i=0; i<numfiles; i++) {
            sprintf (inname, "%s/%03u.png", argv[1], basenum + i);
            sprintf (outname, "%s/%03u.blah", argv[2], basenum + i);
            //convertimg (inname, outname);
            printf ("Processed %s to %s\n", inname, outname);
        }
    return 0;
    }
    

    Program input

    test aaa dest/bbbb 100 10
    

    Program output

    Processed aaa/100.png to dest/bbbb/100.blah
    Processed aaa/101.png to dest/bbbb/101.blah
    Processed aaa/102.png to dest/bbbb/102.blah
    Processed aaa/103.png to dest/bbbb/103.blah
    Processed aaa/104.png to dest/bbbb/104.blah
    Processed aaa/105.png to dest/bbbb/105.blah
    Processed aaa/106.png to dest/bbbb/106.blah
    Processed aaa/107.png to dest/bbbb/107.blah
    Processed aaa/108.png to dest/bbbb/108.blah
    Processed aaa/109.png to dest/bbbb/109.blah