如何让用户在我的C程序中命名output.txt文件?

时间:2022-05-27 07:09:30

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

如何让用户能够命名输出.txt文件?这就是我现在所拥有的一切。

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

3 个解决方案

#1


1  

You can read the input from user and append .txt

您可以从用户读取输入并附加.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");

#2


1  

You can use the array argv :

你可以使用数组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

然后编译并执行代码:./ foo output.txt

#3


0  

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

在函数fopen中,第一个参数是te文件的名称,现在你使用的是常量,但是你可以使用一个变量(一个字符串)。您可以从scanf或通过argv或GUI获取它

#1


1  

You can read the input from user and append .txt

您可以从用户读取输入并附加.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");

#2


1  

You can use the array argv :

你可以使用数组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

然后编译并执行代码:./ foo output.txt

#3


0  

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

在函数fopen中,第一个参数是te文件的名称,现在你使用的是常量,但是你可以使用一个变量(一个字符串)。您可以从scanf或通过argv或GUI获取它