/ / Sto cercando di impostare un flusso di file o qualcosa del genere, ma sono molto confuso su cosa dovrei fare - c ++, fstream, ifstream, ofstream

Sto provando a creare un flusso di file o qualcosa del genere, ma sono molto confuso su cosa dovrei fare - c ++, fstream, ifstream, ofstream

#include <iostream>
#include <fstream>

int main() {
std::ofstream outfile("text.txt", ios::trunc);
std::ifstream infile("text.txt", ios::trunc);

outfile.seekp(0);

std::cout << "This is a file";

infile.seekg(0, ios::end);
int length = infile.tellg();
infile.read(0, length);

infile.close();
outfile.close();
return 0;
}

Penso di avere l'idea alla base, ma mi sentotipo (e sono abbastanza sicuro) non ho idea di cosa sto facendo. L'ho cercato e tutto mi ha confuso. Ho letto un riferimento C ++ e poi l'ho cercato su Google, ma ancora non capisco cosa sto facendo di sbagliato.

#include <iostream>
#include <fstream>
#include <cstring>

int main() {
std::fstream file("text.txt", std::ios_base::in | std::ios_base::out);

file << "This is a file";
int length = file.tellg();

std::string uberstring;
file >> uberstring;
std::cout << uberstring;

char *buffer = new char[length + 1];
file.read(buffer, length);
buffer[length] = "";

file.close();
delete [] buffer;

return 0;
}

Ho provato questo, ma non stampa nulla. Perché non funziona?

risposte:

1 per risposta № 1

Se vuoi leggere e scrivere nello stesso file, usa un normale std::fstream ... non è necessario tentare e aprire lo stesso file di entrambi a ifstream e ofstream. Inoltre, se si desidera scrivere dati nel file, utilizzare il operator<< sul reale fstream oggetto istanza, no std::cout ... che scriverà semplicemente ovunque std::cout è impostato, che in genere è la console. Infine, la chiamata a read deve tornare in un buffer, non è possibile utilizzarlo NULL come argomento. Quindi il tuo codice cambierà nel modo seguente:

int main()
{
std::fstream file("text.txt", ios_base::in | ios_base::out);

//outfile.seekp(0); <== not needed since you just opened the file

file << "This is a file"; //<== use the std::fstream instance "file"

//file.seekg(0, ios::end); <== not needed ... you"re already at the end
int length = file.tellg();

//you have to read back into a buffer
char* buffer = new char[length + 1];
infile.read(buffer, length);
buffer[length] = ""; //<== NULL terminate the string

file.close();
delete [] buffer;

return 0;
}