从服务器中不同位置的命令行参数传递的打开文件名
Open file name passed from commandline argument that is in different location in the server
我想打开我从命令行发送的文件名,但文件在/home/docs/cs230中。下面是我尝试的代码,但当我试图在linux中编译时,它显示了错误:
int main(int arg, char* args[1]) {
// Open the file
newfile = fopen("/home/docs/cs230/"+args[1], "w+b");
}
由于这是c++,我们可以这样使用std::string
:
int main(int arg, char* args[]) {
// Open the file
std::string path( "/home/docs/cs230/" ) ;
path+= args[1] ;
std::cout << path << std::endl ;
FILE *newfile = fopen( path.c_str(), "w+b");
}
Mats还做了一个很好的评论,在c++中我们将使用fstream,您可以在链接中阅读更多信息。
由于这是c++,我建议这样做:
int main(int argc, char *argv[])
// Please don't make up your own names for argc/argv, it just confuses people!
{
std::string filename = "/home/docs/cs230/";
filename += argv[1];
newfile = fopen(filename.c_str(), "w+b");
}
[虽然要使它完全c++,你应该使用fstream
,而不是FILE
如果你想坚持使用指针,你可以连接字符串(char*)
const char* path = "/home/docs/cs230/";
int size1 = sizeof(argv[1]);
int size2 = sizeof(path);
const char* result = new char[size1 + size2 + 2];
result[size1 + size2 + 1] = ' ';
memcpy( result, path, size1 );
memcpy( &result[ size1 ], argv[1], size2 );
不是一个推荐的选项,但是这里有很多可能性
相关文章:
- 如何在不传递命令行参数的情况下在 c++ 中设置环境变量
- 如何在 Android/NDK 上将命令行参数从 gradlew.bat 传递到 Clang
- 在VS2013中使用devenv (C++)传递命令行参数argv
- 需要有关如何设置getopt_long以正确传递命令行参数的建议
- 如何在C++中通过命令行参数传递常量 int
- 在 main() 中传递C++命令行参数,但要做同样的工作
- 将文本文件而不是用户输入作为命令行参数传递
- 将字符串作为命令行参数传递
- 如何将命令行参数与c++中的选项一起传递给函数
- 如何在 Visual Studio 2015 调试中将'%'符号作为命令行参数 (argv) 传递?
- C++ LPCTSTR 如何将命令行参数传递给子进程
- C++如何在进程之间传递命令行参数
- 将命令行参数输入文件传递给要分析的类
- 将文件的每一行作为命令行参数传递给二进制文件
- 将Unicode命令行参数传递到控制台应用程序
- Linux将连续输出作为命令行参数传递
- 在C++中传递命令行参数
- Boost::Program_options,传递未知的命令行参数
- 创建进程不会将命令行参数传递给新进程的主函数
- 从服务器中不同位置的命令行参数传递的打开文件名