2
A
回答
3
你问有关如何在命令行中得到一个字符串来命名要打开的文件?
#include <iostream>
#include <cstdlib>
#include <fstream>
int main(int argc,char *argv[]) {
if(2>argc) {
std::cout << "you must enter a filename to write to\n";
return EXIT_FAILURE;
}
std::ofstream fout(argv[1]); // open a file for output
if(!fout) {
std::cout << "error opening file \"" << argv[1] << "\"\n";
return EXIT_FAILURE;
}
fout << "Hello, World!\n";
if(!fout.good()) {
std::cout << "error writing to the file\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
+0
非常好!谢谢。 :) –
-1
您需要解析命令行参数并将其中的一个用作文件的文件名。看到这样的代码:
#include <stdio.h>
int main (int argc, char *argv[])
{
if (argc != 2) /* argc should be 2 for correct execution */
{
/* We print argv[0] assuming it is the program name */
printf("usage: %s filename", argv[0]);
}
else
{
// We assume argv[1] is a filename to open
FILE *file = fopen(argv[1], "r");
/* fopen returns 0, the NULL pointer, on failure */
if (file == 0)
{
printf("Could not open file\n");
}
else
{
int x;
/* read one character at a time from file, stopping at EOF, which
indicates the end of the file. Note that the idiom of "assign
to a variable, check the value" used below works because
the assignment statement evaluates to the value assigned. */
while ((x = fgetc(file)) != EOF)
{
printf("%c", x);
}
fclose(file);
}
}
}
在这里看到更多的细节:http://www.cprogramming.com/tutorial/c/lesson14.html
相关问题
- 1. 如何使用命令行运行一个maven创建的jar文件
- 2. 用代码签名创建使用命令行的ipa文件
- 3. 如何在C创建使用execl的命令文件
- 4. 批量命令使用txt文件的第一行来创建一个文件
- 5. 使用命令行的参数创建一个C++程序
- 6. 如何用一个命令创建这组多个文件?
- 7. 如何在C中创建命令行?
- 8. 如何使用命令行创建输出文件?
- 9. 如何使用命令行创建WAR文件?
- 10. 如何使用命令行创建批处理文件?
- 11. 如何为C++创建一个命令行模拟器GUI
- 12. 用命令行创建HTML文件
- 13. Unix命令创建NEXT文件名。
- 14. 如何创建一个.jar运行命令行应用程序
- 15. 创建一个文件夹名称变量DOS命令
- 16. 使用IntelliJ IDEA中的命名约定创建一个文件
- 17. 使用bat命令创建文件夹
- 18. 如何(有可能)创建运行多个命令的hg命令别名?
- 19. 使用Log命令创建一个日志文件?
- 20. 用python创建命令行别名
- 21. 命名一个可执行文件c
- 22. 使用命令行参数在C程序中创建多个文件
- 23. 建立一个使用命令行一个Visual Studio C++项目
- 24. 如何创建一个unix命令
- 25. 如何使用for-loop通过windows 10命令行创建多个文件?
- 26. 以一个命令行参数作为文件名,打开C++
- 27. 用Eclipse创建的文件但不能用命令行创建的文件
- 28. 如何使用SVN命令查找文件的创建者
- 29. 如何使用“find”命令获取昨天创建的文件?
- 30. 如何在Minix 3的命令行上创建C程序可执行文件?
这是个玩笑..? – Beginner
哪个平台?你可以使用提升? – FailedDev
罗马B.为什么我会开玩笑这件事?没有任何意义。 –