【问题标题】:Open file name passed from commandline argument that is in different location in the server从位于服务器不同位置的命令行参数传递的打开文件名
【发布时间】:2013-04-16 01:06:48
【问题描述】:

我想打开从命令行发送的文件名,但文件位于 /home/docs/cs230 中。以下是我尝试过的代码,但是当我尝试在 linux 中编译时显示错误:

int main(int arg, char* args[1]) {
   // Open the file 
   newfile = fopen("/home/docs/cs230/"+args[1], "w+b");
}

【问题讨论】:

    标签: c++ linux file-io arguments fopen


    【解决方案1】:

    由于这是 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,您可以在链接中阅读更多信息。

    【讨论】:

      【解决方案2】:

      由于这是 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,而不是文件

      【讨论】:

        【解决方案3】:

        如果你想坚持使用指针,你可以连接字符串 (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] = '\0';
        memcpy( result, path, size1 );
        memcpy( &result[ size1 ], argv[1], size2 );
        

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-10-11
          • 2013-05-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多