Kuinka lukea tiedostosta C++:ssa?

C++:ssa tiedostonkäsittelyn avulla käyttäjät voivat lukea, kirjoittaa ja päivittää tietoja ulkoiseen tiedostoon. Tässä artikkelissa opimme lukemaan tietoja tiedostosta C++:ssa.

Lue tiedostosta C++:ssa

Voit lukea tiedoston sisällön C++:ssa käyttämällä std::ifstream> (syöttötiedostovirta) luodaksesi syöttövirran tiedostoon. Voimme sitten käyttää std::getline()-funktiota tietojen lukemiseen tästä tiedostosta ja tallentamisesta johonkin paikalliseen merkkijonoobjektiin.

Lähestyä

  1. Avaa ensin tiedosto komennolla std:: ifstream inputFile('filePath').>
  2. Then, c> ihme, onko tiedosto avattu onnistuneesti vai ei käytetä is_open()> joka palaa false if> tiedostoa ei voitu avata ja se on muuten tosi.
  3. Lue tiedosto rivi riviltä using> std:: getline()> function and print the content.>
  4. Finally, close the file using> std::fstream::close()> .>

C++-ohjelma tiedostosta lukemiseen

Alla oleva esimerkki osoittaa, kuinka voimme avata ja lukea input.txt-nimisen tiedoston sisällön C++:ssa.

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

Lähtö

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

Aika monimutkaisuus: O(n), missä n on luettavien merkkien määrä.
Tilan monimutkaisuus: O(n)