从服务器中不同位置的命令行参数传递的打开文件名

Open file name passed from commandline argument that is in different location in the server

本文关键字:命令行 参数传递 文件名 位置 服务器      更新时间:2023-10-16

我想打开我从命令行发送的文件名,但文件在/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 );

不是一个推荐的选项,但是这里有很多可能性