Twitter iPhone pliant OnePlus 11 PS5 Disney+ Orange Livebox Windows 11

lecture d'un fichier

3 réponses
Avatar
JBB
Bonjour à tous,

Ça doit être tout con mais y a t' il un moyen de lire un fichier d'un seul coup.

Il y a le std::getLine qui lit une ligne, mais y a t' il un getAllfile ?

Sinon comment faire:

actuellement je suis a un truc du genre:

ostringstream datas;
while(!fichier.eof())
{
string s;
getline(fichier,s);
datas << s << endl;
}
return datas.str();

Merci,

JBB

3 réponses

Avatar
Michael DOUBEZ

Ça doit être tout con mais y a t' il un moyen de lire un fichier d'un
seul coup.
Sinon comment faire:


There are to methods:
1. Get the size of the file, allocate enough memory and read it:
2. outpout the stream buffer in a ostringstream and get the result.


Open a filebuf (you can also use th rdbuf() method of fstream).
//open file
filebuf fb;
fb.open("test.txt",ios::in);

1: read bytes
// get file size
const long sizeû.pubseekoff (0,ios::end,ios::in);
fb.pubseekpos (0,ios::in);
// file data
char* buffer=new char[size];
// get file data
fb.sgetn(buffer,size);
cout<<buffer;

2: read into a stream
ostringstream os;
os<<&fb;
cout<<os.str();

Reading into a stream is more compact but requires more memory and copy.

--
Michael

Avatar
Michael DOUBEZ
[en anglais]


Désolé, je me suis trompé de langue.

--
Michael

Avatar
James Kanze
On Jun 12, 1:43 pm, Michael DOUBEZ wrote:

Ça doit être tout con mais y a t' il un moyen de lire un
fichier d'un seul coup. Sinon comment faire:


There are to methods:
1. Get the size of the file, allocate enough memory and read it:
2. outpout the stream buffer in a ostringstream and get the result.

Open a filebuf (you can also use th rdbuf() method of fstream).
//open file
filebuf fb;
fb.open("test.txt",ios::in);

1: read bytes
// get file size
const long sizeû.pubseekoff (0,ios::end,ios::in);
fb.pubseekpos (0,ios::in);
// file data
char* buffer=new char[size];
// get file data
fb.sgetn(buffer,size);
cout<<buffer;


Note que cette méthode n'est pas garantie. Pour commencer, ce
n'est même pas garanti que tu peux convertir le type de retour
du 'pubseekoff' en long. Et dans le cas où la conversion marche,
rien ne dit que la valeur ainsi obtenue ait un rapport
quelconque avec la taille du fichier.

Dans la pratique, ça marcherait en général sous Unix, et sous
Windows si le fichier est ouvert en binary. (Si le fichier est
ouvert en mode text, sous Windows, la taille obtenue ainsi sera
prèsque toujours plus grande que la taille réele.)

--
James Kanze (GABI Software) email:
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34