Reputation: 25
So, like how the Linux terminal works.
If I do something like ls -l
and type in the command ls -l > hello.txt
, it writes whatever was in ls -l
to hello.txt
.
I'm making a terminal of my own and I'm trying to make it so that when a user types in that same command ls -l > asdf.txt
that it writes out ls -l to whatever text file that user inputs.
So here is what I have. My mini-terminal shell works already.
FILE *fp
if (strcmp(args[1], ">") == 0) {
fp = freopen(args[2], "w+", stdout);
}
fclose(fp);
How would I go to outputting whatever is in the 0th argument into the text file? So like, w > hello.txt
would output into hello.txt
?
Upvotes: 1
Views: 153
Reputation: 13786
Depends on how you execute the ls command, you can check out popen, it will run the command, and then returns a FILE, which you can read the output of the command from, and then you could write the output into the file for redirection. For example:
FILE *fin = popen("/bin/ls -l", "r");
if (!fp) { ... //handle error }
FILE *fout = freopen(args[2], "w", stdout);
char c;
while ((c = fgetc(fin)) != EOF) {
fputc(c, fout);
}
pclose(fin);
fclose(fout);
Upvotes: 1
Reputation: 6126
Assuming you are correct with your arguments (args) you can do the following:
char buffer [1024];
FILE *fp
if (strcmp(args[1], ">") == 0) {
fp = freopen(args[2], "w+", stdout);
} else {return; }
FILE *cmd;
cmd = popen(args[0],"r");
if(cmd == NULL)
return;
while (fgets(buffer,sizeof(buffer)-1,cmd)!=NULL)
{
fprintf(fp,"%s",buffer);
}
fclose(fp);
pclose(cmd);
Upvotes: 1