I have the following program that writes a user’s input to a file. Currently the file to be written to is predefined; however, I was wanting allow the user to define the file name from command prompt. What would be the best way to add this functionality? I am having trouble getting my head around how I would make the string entered by the user an argument in the fopen() function. Should I use scanf() or create another getchar() while loop store the chars in an array and then create a variable as the argument of fopen() or something?
#include <stdio.h>
int main()
{
char c;
FILE *fp;
fp = fopen("file.txt", "w");
while ((c = getchar()) != EOF)
{
putc(c, fp);
}
return 0;
}
That’s what the arguments to main are for:
If you followed this, you might wonder what is in
argv[0]. That’s where the program name is. Some operating system environments put the full path to the executable file there. Others put only the program name. Others still put what was typed.For the command
../../bin/someprogramon Windows,
argv[0]is"C:\\Documents and Settings\\User\bin\\someprogram.exe"on Linux/bash,
argv[0]is../../bin/someprogramon Ultrix/csh, (I think)
argv[0]is/home/username/bin/someprogram