Kā lasīt no faila programmā C++?

Programmā C++ failu apstrāde ļauj lietotājiem lasīt, rakstīt un atjaunināt datus ārējā failā. Šajā rakstā mēs uzzināsim, kā nolasīt dažus datus no faila programmā C++.

Lasīt no faila programmā C++

Lai lasītu faila saturu programmā C++, mēs varam izmantot std::ifstream> (ievades faila straume), lai izveidotu faila ievades straumi. Pēc tam mēs varam izmantot funkciju std::getline(), lai nolasītu datus no šī faila un saglabātu tos kādā vietējā virknes objektā.

Pieeja

  1. Vispirms atveriet failu, izmantojot std:: ifstream inputFile('filePath').>
  2. Then, c> heck, ja fails ir veiksmīgi atvērts vai netiek izmantots is_open()> kas atgriežas false if> failu nevarēja atvērt un pretējā gadījumā tas ir patiess.
  3. Izlasiet failu rindiņu pēc rindas using> std:: getline()> function and print the content.>
  4. Finally, close the file using> std::fstream::close()> .>

C++ programma lasīšanai no faila

Tālāk sniegtajā piemērā ir parādīts, kā mēs varam atvērt un nolasīt faila ar nosaukumu input.txt saturu C++ valodā.

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

Izvade

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

Laika sarežģītība: O(n), kur n ir nolasāmo rakstzīmju skaits.
Telpas sarežģītība: O(n)