Skip to content

Instantly share code, notes, and snippets.

@Mizux
Last active October 13, 2022 22:19
Show Gist options
  • Save Mizux/963623b05fca012b0cf1c702ae83b160 to your computer and use it in GitHub Desktop.
Save Mizux/963623b05fca012b0cf1c702ae83b160 to your computer and use it in GitHub Desktop.
c++ read/write to a file
#include <cstdio>
#include <iostream>
#include <filesystem>
#include <fstream>
namespace fs = std::filesystem;
int main()
{
const std::string filename = std::tmpnam(nullptr);
{
std::cout << "File: " << filename << std::endl;
FILE* fp = std::fopen(filename.c_str(), "w+");
const std::string data =
"1\n"
"11\n"
"21\n"
"1211\n"
"111221\n";
std::fputs(data.c_str(), fp);
std::fclose(fp);
}
{
std::cout << "reading..." << std::endl;
fs::path path = filename;
std::ifstream file(path, std::ifstream::in);
//std::ifstream file;
//file.open(path, std::ifstream::in);
char c = file.get();
while (file.good()) {
std::cout << c;
c = file.get();
}
file.close();
//std::cout << file << std::endl;
}
std::remove(filename.c_str());
}

ref: https://coliru.stacked-crooked.com/view?id=3227f6a1752f9fec

g++ -std=c++23  -O2 -Wall -Wextra -pedantic -pthread -pedantic-errors main.cpp -lm  -latomic  && ./a.out
/tmp/ccw6Ksys.o: In function `main':
main.cpp:(.text.startup+0xc): warning: the use of `tmpnam' is dangerous, better use `mkstemp'

possible output

File: /tmp/fileb0L1Ln
reading...
1
11
21
1211
111221
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment