Skip to content

Instantly share code, notes, and snippets.

@pniedzwiedzinski
Last active February 20, 2020 21:33
Show Gist options
  • Save pniedzwiedzinski/f922166afb92998485417d9b5f01c812 to your computer and use it in GitHub Desktop.
Save pniedzwiedzinski/f922166afb92998485417d9b5f01c812 to your computer and use it in GitHub Desktop.
writing to file
// Author: Patryk Niedźwiedziński
#include <iostream>
#include <fstream>
using namespace std;
bool writeText(string filename, char* text) {
ofstream file(filename, ios::app); // append
if (!file.is_open()) { // sprawdza czy udało się dostać do pliku
// jeżeli nie to zwróć `true` jako że jest error
return true;
}
file << text; // dopisujemy text do pliku
file.close(); // zamykamy plik, to trzeba robić że system nie zwariował
return false; // zwracamy false jako że nie wystąpił żaden błąd
}
bool writeBinary(string filename, string text) {
ofstream file(filename, ios::app | ios::binary); // append ale binary
if (!file.is_open()) { // to samo co wyżej
return true;
}
for (int i = 0; i < text.length(); i++) { // dla każdego znaku
file.write((char*)&text[i], sizeof(char)); // zapisujemy ten znak (musi być ta magia pointerowa), drugi argument to ile bajtów ma iść po tym pointerze
}
file.close();
return false;
}
int main()
{
bool err = writeText("test.txt", (char*) "Testowy tekst");
if (err) {
cout << "Salut to the General Failure!";
}
err = writeBinary("test.bin", "123");
if (err) {
cout << "Salut to the General Failure!";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment