Shant Cancik
Shant Cancik

Reputation: 113

How do I let the user name the output.txt file in my C program?

How to I give the user the ability to name the output .txt file? Here is all I have right now.

FILE *f = fopen("output.txt", "a");

Upvotes: 0

Views: 81

Answers (3)

jabujavi
jabujavi

Reputation: 487

In the function fopen the first argument is the name for te file, now your are using a constant but you can use a variable(a string). You could take it from scanf or via argv or via GUI

Upvotes: 0

adricadar
adricadar

Reputation: 10209

You can read the input from user and append .txt

char fileName[30];
// ...
scanf("%25s", fileName); // max 25 characters because .txt have 4 (25+4 = 29)
strcat(fileName, ".txt"); // append .txt extension
// ...
FILE *f = fopen(fileName, "a");

Upvotes: 1

alifirat
alifirat

Reputation: 2937

You can use the array argv :

int main(int argc, char **argv) {
    if(argc == 2) {
        FILE *f = fopen(argv[1], "a");      
    }
    return 0;
}

Then when you compile and execute the code : ./foo output.txt

Upvotes: 1

Related Questions