2011-12-02 12 views
2

私はC++のチュートリアルをやっていますが、これまではかなりうまいです。しかし、私が知り得た知識を混乱させ、強制して、私に頭痛を与えるものが1つあります。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

コマンドラインパラメータを解析して、ファイルのファイル名としてその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++のサブセットです); –

関連する問題