logo

C++ でファイルから読み取るにはどうすればよいですか?

C++ では、ファイル処理により、ユーザーは外部ファイルへのデータの読み取り、書き込み、更新が可能になります。この記事では、C++ でファイルからデータを読み取る方法を学びます。

C++ でのファイルからの読み取り

C++ でファイルの内容を読み取るには、 std::ifstream> (入力ファイル ストリーム) ファイルへの入力ストリームを作成します。次に、 std::getline() 関数を使用して、このファイルからデータを読み取り、ローカル文字列オブジェクトに保存します。



アプローチ

  1. まず、std:: を使用してファイルを開きます。ifstream inputFile('filePath').>
  2. Then, c>ファイルが正常に開かれたか、ファイルが使用されていないかを確認してください。is_open()>それは戻ってきますfalse if>ファイルを開くことができませんでした。それ以外の場合は true。
  3. ファイルを一行ずつ読み取る using> std:: getline()> function and print the content.>
  4. Finally, close the file using> std::fstream::close()> .>

ファイルから読み取る C++ プログラム

以下の例は、C++ で input.txt という名前のファイルを開いて内容を読み取る方法を示しています。

C++








// C++ program to read from a file> #include> #include> #include> using> namespace> std;> > int> main()> {> >// Open the input file named 'input.txt'> >ifstream inputFile(>'input.txt'>);> > >// Check if the file is successfully opened> >if> (!inputFile.is_open()) {> >cerr <<>'Error opening the file!'> << endl;> >return> 1;> >}> > >string line;>// Declare a string variable to store each> >// line of the file> > >// Read each line of the file and print it to the> >// standard output stream> >cout <<>'File Content: '> << endl;> >while> (getline(inputFile, line)) {> >cout << line << endl;>// Print the current line> >}> > >// Close the file> >inputFile.close();> > >return> 0;> }>

>

>

出力

File Content:  Hey Geek! Welcome to GfG. Happy Coding.>

時間計算量: O(n)、n は読み取られる文字数です。
空間の複雑さ: O(n)