bqui56
bqui56

Reputation: 2121

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

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;
}

Upvotes: 6

Views: 47971

Answers (4)

Pheonix
Pheonix

Reputation: 6052

Use argc and argv

#include <stdio.h>

int main(int argc, char **argv)
{
    char c;
    FILE *fp;
    if(argc < 2){
        printf("Usage : ./a.out <filename>");
        exit(0);
    }

    fp = fopen(argv[1], "w");

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

    return 0;
}

Upvotes: 1

wallyk
wallyk

Reputation: 57774

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

Upvotes: 10

Christopher Neylan
Christopher Neylan

Reputation: 8272

There are many functions to read in strings; fgets and scanf, for example. The problem is that you need to know the max number of characters that you want to read in before-hand. If this is ok for you, then use one of those. If not, then you'll have to write your own function to read in a dynamic string, like here.

Upvotes: 0

user97370
user97370

Reputation:

Define main like this:

int main(int argc, char *argv[]) {

And then use argv: an array of the command-line arguments. argv[0] is the name of the command as entered at the command line, argv[1] is the first argument.

    fp = fopen(argv[1], "w');

You probably want to check that argc > 1 to avoid an out-of-bounds array access.

Upvotes: 0

Related Questions