web-dev-qa-db-fra.com

Lire le contenu du fichier dans une chaîne en C ++

Duplicate possible:
Quel est le meilleur moyen de transformer un fichier en std :: string en c ++?

Dans les langages de script tels que Perl, il est possible de lire un fichier dans une variable d'un coup.

    open(FILEHANDLE,$file);
    $content=<FILEHANDLE>;

Quel serait le moyen le plus efficace de faire cela en C++?

72
sonofdelphi

Comme ça:

#include <fstream>
#include <string>

int main(int argc, char** argv)
{

  std::ifstream ifs("myfile.txt");
  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

  return 0;
}

La déclaration

  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

peut être divisé en

std::string content;
content.assign( (std::istreambuf_iterator<char>(ifs) ),
                (std::istreambuf_iterator<char>()    ) );

ce qui est utile si vous voulez simplement écraser la valeur d'une variable std :: string existante.

156
Maik Beckmann

Le moyen le plus efficace, mais pas le C++, serait:

   FILE* f = fopen(filename, "r");

   // Determine file size
   fseek(f, 0, SEEK_END);
   size_t size = ftell(f);

   char* where = new char[size];

   rewind(f);
   fread(where, sizeof(char), size, f);

   delete[] where;

#EDIT - 2

Je viens de tester le std::filebuf variante aussi. On dirait que cela peut être appelé la meilleure approche C++, même si ce n'est pas vraiment une approche C++, mais plutôt un wrapper. Quoi qu'il en soit, voici le morceau de code qui fonctionne presque aussi vite que C ordinaire.

   std::ifstream file(filename, std::ios::binary);
   std::streambuf* raw_buffer = file.rdbuf();

   char* block = new char[size];
   raw_buffer->sgetn(block, size);
   delete[] block;

J'ai fait un repère rapide ici et les résultats suivent. Le test a été effectué en lisant un fichier binaire 65536K avec le fichier approprié (std::ios:binary et rb) modes.

[==========] Running 3 tests from 1 test case.
[----------] Global test environment set-up.
[----------] 4 tests from IO
[ RUN      ] IO.C_Kotti
[       OK ] IO.C_Kotti (78 ms)
[ RUN      ] IO.CPP_Nikko
[       OK ] IO.CPP_Nikko (106 ms)
[ RUN      ] IO.CPP_Beckmann
[       OK ] IO.CPP_Beckmann (1891 ms)
[ RUN      ] IO.CPP_Neil
[       OK ] IO.CPP_Neil (234 ms)
[----------] 4 tests from IO (2309 ms total)

[----------] Global test environment tear-down
[==========] 4 tests from 1 test case ran. (2309 ms total)
[  PASSED  ] 4 tests.
39

Le plus efficace est de créer un tampon de la taille correcte, puis de lire le fichier dans le tampon.

#include <fstream>
#include <vector>

int main()
{
    std::ifstream       file("Plop");
    if (file)
    {
        /*
         * Get the size of the file
         */
        file.seekg(0,std::ios::end);
        std::streampos          length = file.tellg();
        file.seekg(0,std::ios::beg);

        /*
         * Use a vector as the buffer.
         * It is exception safe and will be tidied up correctly.
         * This constructor creates a buffer of the correct length.
         * Because char is a POD data type it is not initialized.
         *
         * Then read the whole file into the buffer.
         */
        std::vector<char>       buffer(length);
        file.read(&buffer[0],length);
    }
}
12
Martin York

Il devrait y avoir aucun \0 dans des fichiers texte.

#include<iostream>
#include<fstream>

using namespace std;

int main(){
  fstream f(FILENAME, fstream::in );
  string s;
  getline( f, s, '\0');

  cout << s << endl;
  f.close();
}
6
Draco Ater

Cela dépend de nombreux facteurs, tels que la taille du fichier, son type (text/binary), etc.

unsigned int FileRead( std::istream & is, std::vector <char> & buff ) {
    is.read( &buff[0], buff.size() );
    return is.gcount();
}

void FileRead( std::ifstream & ifs, string & s ) {
    const unsigned int BUFSIZE = 64 * 1024; // reasoable sized buffer
    std::vector <char> buffer( BUFSIZE );

    while( unsigned int n = FileRead( ifs, buffer ) ) {
        s.append( &buffer[0], n );
    }
}
2
anon

peut-être pas le plus efficace, mais lit les données sur une seule ligne:

#include<iostream>
#include<vector>
#include<iterator>

main(int argc,char *argv[]){
  // read standard input into vector:
  std::vector<char>v(std::istream_iterator<char>(std::cin),
                     std::istream_iterator<char>());
  std::cout << "read " << v.size() << "chars\n";
}
1
catwalk

Voici une méthode basée sur les itérateurs.

ifstream file("file", ios::binary);
string fileStr;

istreambuf_iterator<char> inputIt(file), emptyInputIt
back_insert_iterator<string> stringInsert(fileStr);

copy(inputIt, emptyInputIt, stringInsert);
1
academicRobot