Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define and pass in a file name to fopen() from command line?

Tags:

c

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;
}
like image 408
bqui56 Avatar asked Dec 24 '11 16:12

bqui56


1 Answers

That's what the arguments to main are for:

#include <stdio.h>

int main(int argc, char **argv)
{
    char c;
    FILE *fp;

    if (argc >= 2)
         fp = fopen(argv[1], "w");
    else fp = fopen("file.txt", "w");

    while ((c = getchar()) != EOF)
    {
        putc(c, fp);
    }

    return 0;
}

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/someprogram

on Windows, argv[0] is "C:\\Documents and Settings\\User\bin\\someprogram.exe"
on Linux/bash, argv[0] is ../../bin/someprogram
on Ultrix/csh, (I think) argv[0] is /home/username/bin/someprogram

like image 156
wallyk Avatar answered Oct 03 '22 09:10

wallyk