C ++
 Computer >> コンピューター >  >> プログラミング >> C ++

C ++でテキストファイルを読み取る方法は?


これは、テキストファイルを読み取るためのC++プログラムです。

入力

tpoint.txt is having initial content as
“Tutorials point.”

出力

Tutorials point.

アルゴリズム

Begin
   Create an object newfile against the class fstream.
   Call open() method to open a file “tpoint.txt” to perform write operation using object newfile.
   If file is open then
      Input a string “Tutorials point" in the tpoint.txt file.
      Close the file object newfile using close() method.
   Call open() method to open a file “tpoint.txt” to perform read operation using object newfile.
   If file is open then
      Declare a string “tp”.
      Read all data of file object newfile using getline() method and put it into the string tp.
      Print the data of string tp.
   Close the file object newfile using close() method.
End.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
   fstream newfile;
   newfile.open("tpoint.txt",ios::out);  // open a file to perform write operation using file object
   if(newfile.is_open()) //checking whether the file is open {
      newfile<<"Tutorials point \n"; //inserting text
      newfile.close(); //close the file object
   }
   newfile.open("tpoint.txt",ios::in); //open a file to perform read operation using file object
   if (newfile.is_open()){ //checking whether the file is open
      string tp;
      while(getline(newfile, tp)){ //read data from file object and put it into string.
         cout << tp << "\n"; //print the data of the string
      }
      newfile.close(); //close the file object.
   }
}

出力

Tutorials point

  1. Androidアプリで簡単なテキストファイルを読む方法は?

    この例は、Androidアプリで簡単なテキストファイルを読み取る方法を示しています。 ステップ1 − Android Studioで新しいプロジェクトを作成し、[ファイル]⇒[新しいプロジェクト]に移動して、新しいプロジェクトを作成するために必要なすべての詳細を入力します。 新しいAndroidリソースディレクトリ(raw.xml)を作成し、res/rawにテキストファイルを追加します ステップ2 −次のコードをres / layout/activity_main.xmlに追加します。 <?xml version="1.0" encoding="utf

  2. Rubyでファイルを読み書きする方法(例付き)

    今日は、Rubyでファイルを読み書きして、コンテンツを抽出し、新しいファイルを作成し、必要な情報を見つける方法を学びます。 これから説明します : コンテンツ 1Rubyでファイルを読み取る方法 2Rubyでファイルに書き込む方法 3つのRubyファイルメソッド 4つのディレクトリ操作 5FileUtilsモジュールの使用方法 6まとめ 6.1関連 やってみましょう! Rubyでファイルを読み取る方法 次のようにRubyでファイルを読み取ることができます: ファイルを開く 、open メソッド。 ファイルを読む 、ファイル全体、行ごと、または特定のバイト数。 ファイルを