0

I found some code online to write a binary file, but when I want to execute it, the compiler gives me an error

unknown type name 'fs'

How can I fix this?

#include <fstream>

namespace std{
    string token = "token";
    std::ofstream fs("example.bin", ios::out | ios::binary | ios::app);
    fs.write(token, sizeof token);
    fs.close();
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 7
    If this is a literal copy of the code you found online, consider not going back to wherever you found this code. – user4581301 Jul 22 '20 at 18:02
  • 3
    So many things wrong with only four lines of code. Cutting and pasteing code from the internet is no way at all to learn C++. – john Jul 22 '20 at 18:05
  • 1
    I strongly suggest you get a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and reiterate the fundamentals of C++. – Lukas-T Jul 22 '20 at 18:06
  • 1
    You found a broken piece of code that is ill-formed and doesn't do anything meaningful. You cannot fix it unless you know what you're trying to do. For an analogy: Consider picking up a heap of scrap metal, bringing it to a car mechanic, and ask how to make it work. – eerorika Jul 22 '20 at 18:12
  • You really don't want to use `write()` with a `std::string`. You'll only be writing the overhead or structure of `std::string`, **not the string data**, as the string data is usually dynamically allocated. – Thomas Matthews Jul 22 '20 at 18:13

1 Answers1

4

You can't have non-declaration statements inside of a namespace block. The code to use the std::string and std::ofstream objects needs to be inside of a function instead, which can then be declared inside of a namespace if desired. And besides, it is illegal to add new things to the std namespace, anyway.

Also, you can't write() a std::string object in the manner the code is trying to. Not only will it not compile to begin with (the 1st parameter needs a char* pointer), but it is logically wrong anyway since a std::string stores its character data elsewhere in memory, so you would be writing the std::string's internal pointers to that data, not the actual data itself.

Try this instead:

#include <fstream>
#include <string>

namespace my_ns{
    void save() {
        std::string token = "token";
        std::ofstream fs("example.bin", std::ios::binary | std::ios::app);
        fs.write(token.c_str(), token.size());
        fs.close();
    }
}

int main() {
    my_ns::save();
    return 0;
}

Though, I suspect the original code was actually trying to do something more like this instead:

#include <fstream>
#include <string>

using namespace std; // <--

int main() {
    string token = "token";
    ofstream fs("example.bin", ios::binary | ios::app);
    fs.write(token.c_str(), token.size());
    fs.close();
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770