Lenn Van Haverbeke
Lenn Van Haverbeke

Reputation: 121

how to fix "unknown type name 'variable'"?

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();
}

Upvotes: 0

Views: 1983

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 595762

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;
}

Upvotes: 4

Related Questions