Originally Posted by
spank
i want to run a binary with the following arguments
./fis file.in stdout and print to the standard output:
Code:
#include<stdio.h>
int main(int argc , char *argv[])
{
FILE *f=fopen(argv[1],"r");
char x[101];
while(fgets(x,100,f))
fputs(x,(FILE*)argv[2]);
fclose(f);
return 0;
}
Your code doesn't work. fputs() takes a buffer and a file pointer, and argv[2], even if cast to a FILE *, does not make a valid file pointer. You have to call fopen() on argv[2] to get a file pointer.
If you are on Linux, executing ./fis file.in /dev/tty should write the output to your tty. When I write programs that take filenames and want them to handle output to stdout, I either make the output file name optional -- if it's specified, I open and use that file, otherwise I use stdout -- or I use "-" by itself as a command argument to indicate stdout (or stdin if it's in a place where the input file belongs), check for that before trying to open the file, and so on. Here's a quick example of a function to do just that:
Code:
FILE *arg_open(char *fname, char *rw, FILE *default)
{
FILE *fp = default; /* use the default by default... */
if (fname != NULL)
{
if (strcmp(fname, "-") != 0)
{
fp = fopen(fname, rw);
}
}
return fp;
}
This function is called just like fopen() except that it has a third argument that take a file pointer to use as a default. So to get either a named file or stdout (if the user typed "-" on the command line), you'd call it as
Code:
FILE *ofp;
if (argc > 2)
{
ofp = arg_open(argv[2], "w", stdout);
}
else
{
ofp = stdout;
}
There are some things I'm not covering here (like closing the file when the program ends), but you need to learn these things, how they work, and why they work, if you're going to be successful in becomming a C programmer.