开发者

C++ FILE to fstream?

开发者 https://www.devze.com 2023-03-15 14:02 出处:网络
I\'m n开发者_如何学运维ot an expert on this but I have this code: FILE *OUTPUT_FILE; OUTPUT_FILE = fopen(file, \"a+\");

I'm n开发者_如何学运维ot an expert on this but I have this code:

FILE *OUTPUT_FILE;

OUTPUT_FILE = fopen(file, "a+");

fprintf(OUTPUT_FILE, "%s", &keys );

fclose(OUTPUT_FILE);

And I would like to pass it to a fstream syntax

like

ofstream fs;

????

They are included on this function:

int Store(int keys, char *file)

I know this is a C function but since I'm learning C++ I would like to know how do I translate this to a C++

sorry I don't know what else or if fs is compatible to fopen.

More information:

Thanks everybody but it seems its ignoring some values

    int Store(int keys, char *file)
    {


    ofstream output_file("log.txt");
    output_file << keys; 
    output_file.close();

    cout << keys;

    return 0;
    }

when it oututs the file i just see a D i can see the hexadecimal values of the keys on the console but not being printed on the text....


First of all, ALL_CAPS should generally be reserved for macros -- using it for a normal variable holding a FILE * is generally a poor idea.

As far as the rest goes, it would look something like this:

std::fstream output_file(file, std::fstream::in | std::fstream::out | std::fstream::app);
output_file << keys;

That could be a bit wrong, though -- right now your function prototype says keys is an int, but you're passing it to fprintf using the %s format, which is for a string, not an int. As-is, the code produces undefined behavior, and it's not completely certain what you really want. I've taken a guess I think is reasonable, but I'm not quite sure.

Edit: In case you're trying to write out the raw bytes of keys, that would look something like:

output_file.write(reinterpret_cast<char *>(&keys), sizeof(keys));

Thanks for the suggestion @ildjarn.


http://www.cplusplus.com/reference/iostream/ostream/write/

It is important to note that you can use the same C style writing in C++. So all of your C code will work in C++! Which is often time the happier solution, especially for IO that doesn't need to be lightning fast.


To use ofstream:

std::ofstream foo; //Declaring the ofstream object
foo.open("file_name"); //Setting the output file name
foo<<keys; //Now it's ready to take << input!
foo.close(); //When you're done with the file
0

精彩评论

暂无评论...
验证码 换一张
取 消