Hoe lees je uit een bestand in C++?

In C++ kunnen gebruikers met bestandsverwerking gegevens in een extern bestand lezen, schrijven en bijwerken. In dit artikel leren we hoe we bepaalde gegevens uit een bestand in C++ kunnen lezen.

Lezen uit een bestand in C++

Om de inhoud van een bestand in C++ te lezen, kunnen we de std::ifstream> (invoerbestandsstroom) om de invoerstroom naar het bestand te maken. We kunnen dan de functie std::getline() gebruiken om de gegevens uit dit bestand te lezen en deze op te slaan in een lokaal stringobject.

Benadering

  1. Open eerst het bestand met std:: ifstream inputFile('filePath').>
  2. Then, c> Controleer of het bestand succesvol is geopend of niet wordt gebruikt is_open()> dat terugkeert false if> bestand kan niet worden geopend en is anders waar.
  3. Lees het bestand regel voor regel using> std:: getline()> function and print the content.>
  4. Finally, close the file using> std::fstream::close()> .>

C++ Programma om uit een bestand te lezen

Het onderstaande voorbeeld laat zien hoe we de inhoud van een bestand met de naam input.txt in C++ kunnen openen en lezen.

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

Uitvoer

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

Tijdcomplexiteit: O(n), waarbij n het aantal te lezen tekens is.
Ruimtecomplexiteit: O(n)