Hello All,
I need some help with using the system command in C. I am trying to use system command to read the names text files from a particular directory on my PC and save it in another text file.
My code is as follows:
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int system(char*);
int main()
{
char dir_str[50] = "G:\\text"; // this is the directory that has my text files
char command1[100], command2[100];
char temp_file[100]= "G:\\temp.txt"; // this is the temp file to which i will save the names of all the text files that exist in directory G:\text
sprintf(command1,"cd %s",dir_str); //command1 to be dos command to change directory
command1[strlen(command1)]='\0'; //introduced this to eliminate buffer overflow
system(command1); //doesn't seem to do anything
temp_file[strlen(temp_file)]='\0'; // to eliminate buffer overflow
sprintf(command2,"dir *.txt /b > %s",temp_file); //command to copy all .txt files from dir to temp_file ... I would assume dir to be G:\\text 'coz I called the system(command1) but this doesnt do anything
return 0;
}
Someone kindly tell me what I am doing wrong. Interestingly, if I replaced sprintf(command2,"dir *.txt /b > %s",temp_file) with sprintf(command2,"dir *.txt /b > temp.txt") it will create a temp.txt file in the SAME folder from where I am running the program and save ONLY .txt files that are in the SAME folder from where I am running the program. In short, system command doesn't seem to like %s format specifier and string parameter.
Thanks in advance for your help!