Miten C++:ssa saa käsiteltyä tiedostoja? Esim. PHP:ssa tiedoston lukeminen onnistuu näin:
<?php $tiedosto = file_get_contents("tiedosto.txt"); echo $tiedosto; ?>
Miten on C++:an laita? Tarkoituksena olisi siis lisätä tiedostoon tietoa ja lukea tiedostoa.
Tiedostoja käsitellään otsikossa fstream määritellyillä luokilla std::ifstream ja std::ofstream, joista luodut oliot toimivat kuten std::cin ja std::cout. Netistä löytyy yllin kyllin esimerkkejä.
Kiva...
Kysymäsi PHP-funktion voi toteuttaa suunnilleen näin:
#include <string>
#include <fstream>
#include <stdexcept>
std::string file_get_contents(const std::string& filename) {
std::string data;
char buffer[1024];
std::ifstream file(filename.c_str(), std::ios::binary);
if (!file.is_open()) {
throw std::runtime_error("Virhe tiedoston avaamisessa!");
}
while (file) {
file.read(buffer, sizeof(buffer));
data.append(buffer, file.gcount());
if (file.eof()) {
return data;
}
}
throw std::runtime_error("Virhe tiedoston lukemisessa!");
}Aihe on jo aika vanha, joten et voi enää vastata siihen.