I am trying to using C to work with files with different extensions. So this is the code that I have written.
#include <stdio.h>
#include <windows.h>
#include <unistd.h>
#include <conio.h>
void mvjpg(char *arg);
void mvpng(char *arg);
void wincmd(const char *c,...);
int main(int argc,char **argv){
char *ext;
for(int i=1;i<argc;i++){
ext=strrchr(argv[i],'.');
if(ext == NULL)
continue;
if(strcmp(ext,".jpg")==0)
mvjpg(argv[i]);
if(strcmp(ext,".png")==0)
mvpng(argv[i]);
}
return 0;
}
void mvjpg(char *arg){
//Do tasks such as ...
wincmd("move %s Done\\ ",arg); //Here this runs properly
printf("%s\n\n",arg); //This also outputs the file name
wincmd("copy %s JPGs\\ ",arg); //Here the value is gibberish
printf("%s\n\n",arg); //This too outputs the file name
}
void mvpng(char *arg){
//Do tasks such as ...
}
void wincmd(const char *c,...){
char cmd[50];
sprintf(cmd,c);
printf("%s\n",cmd);
system(cmd);
}
The Output is:
D:\Folder1>mv new.jpg
move new.jpg Done\
1 file(s) moved.
new.jpg
copy 6Q½6ⁿ JPGs\
The system cannot find the file specified.
new.jpg
Why is one pointer working in first and in other it is not. The value of pointer is not altered between those commands.
It is unclear why you are using a variable argument list.
It would be much simpler to declare the function like
and within the function to write
Nevertheless this call
invokes undefined behavior because there is not specified the third argument that corresponds to the conversion specification
&sthat is present in the stringc.You need to include header
<stdarg.h>that is designed to deal with variable argument lists and process the unnamed argument using macros defined in the header.Here is a demonstration program.
The program output is