logo

Com llegir des d'un fitxer en C++?

En C++, el maneig de fitxers permet als usuaris llegir, escriure i actualitzar dades en un fitxer extern. En aquest article, aprendrem a llegir algunes dades d'un fitxer en C++.

Llegir des d'un fitxer en C++

Per llegir el contingut d'un fitxer en C++, podem utilitzar el std::ifstream> (seqüència del fitxer d'entrada) per crear el flux d'entrada al fitxer. Aleshores podem utilitzar la funció std::getline() per llegir les dades d'aquest fitxer i emmagatzemar-les en algun objecte de cadena local.



Aproximació

  1. Primer, obriu el fitxer amb std::ifstream inputFile('filePath').>
  2. Then, c>mira si el fitxer s'ha obert correctament o no s'utilitzais_open()>que tornafalse if>El fitxer no es podria obrir i és cert en cas contrari.
  3. Llegiu el fitxer línia per línia using> std:: getline()> function and print the content.>
  4. Finally, close the file using> std::fstream::close()> .>

Programa C++ per llegir des d'un fitxer

L'exemple següent mostra com podem obrir i llegir el contingut d'un fitxer anomenat input.txt en 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;> }>

>

>

Sortida

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

Complexitat temporal: O(n), on n és el nombre de caràcters a llegir.
Complexitat espacial: O(n)