2011-12-02 83 views
2

我正在做一些C++教程,到目前为止我非常善于处理它。但是,有一件事情让我感到困惑,并被迫离开了我的知识,这让我很头疼。如何使用C++的命令行创建一个文件名?

如何使用在命令行上给出的名称创建文件?

+1

这是个玩笑..? – Beginner

+0

哪个平台?你可以使用提升? – FailedDev

+0

罗马B.为什么我会开玩笑这件事?没有任何意义。 –

回答

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

+0

非常有用。谢谢。 :) –

+0

对不起,但他明确要求C++代码。 – slaphappy

+0

C是C++的子集;) –

相关问题