Új hozzászólás Aktív témák

  • Sk8erPeter

    nagyúr

    válasz j0k3r! #769 üzenetére

    Akár úgy is megoldhatod, ahogy itt szerepel: istream::read - C++ Reference

    // read a file into memory
    #include <iostream>
    #include <fstream>
    using namespace std;

    int main () {
    int length;
    char * buffer;

    ifstream is;
    is.open ("test.txt", ios::binary );

    // get length of file:
    is.seekg (0, ios::end);
    length = is.tellg();
    is.seekg (0, ios::beg);

    // allocate memory:
    buffer = new char [length];

    // read data as a block:
    is.read (buffer,length);
    is.close();

    cout.write (buffer,length);

    delete[] buffer;
    return 0;
    }

    Viszonylag primitív (de végül is célravezető) megoldás, a fájl végére ugrik, így tudja meg a fájl méretét, ennek megfelelő helyet foglal, majd vissza az elejére, és elkezdi a beolvasást fájl végéig.

    De emvy megoldás-javaslata is tökéletes.

    ---------------------------------------------------------------------------------------------
    Szerk.:
    (#771) j0k3r!
    persze, a string típus is teljesen jó. :K

    PÉLDA:
    string::push_back

    // string::push_back
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;

    int main ()
    {
    string str;
    ifstream file ("test.txt",ios::in);
    while (!file.eof())
    {
    str.push_back(file.get());
    }
    cout << str;
    return 0;
    }

    Sokkal rövidebb is a kód.

Új hozzászólás Aktív témák