Jak číst ze souboru v C++?

V C++ umožňuje manipulace se soubory uživatelům číst, zapisovat a aktualizovat data do externího souboru. V tomto článku se naučíme číst některá data ze souboru v C++.

Číst ze souboru v C++

Pro čtení obsahu souboru v C++ můžeme použít std::ifstream> (stream vstupního souboru) pro vytvoření vstupního toku souboru. Potom můžeme použít funkci std::getline() k načtení dat z tohoto souboru a jejich uložení do nějakého lokálního řetězcového objektu.

Přístup

  1. Nejprve otevřete soubor pomocí std:: ifstream inputFile('filePath').>
  2. Then, c> zkontrolujte, zda je soubor úspěšně otevřen nebo není používán is_open()> že se vrací false if> jinak soubor nelze otevřít a true.
  3. Přečtěte si soubor řádek po řádku using> std:: getline()> function and print the content.>
  4. Finally, close the file using> std::fstream::close()> .>

C++ Program pro čtení ze souboru

Níže uvedený příklad ukazuje, jak můžeme otevřít a přečíst obsah souboru s názvem input.txt v C++.

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;> }>

Výstup

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

Časová složitost: O(n), kde n je počet znaků, které se mají přečíst.
Vesmírná složitost: O(n)