Home > database >  Can't write to txt file
Can't write to txt file

Time:11-26

I am trying to write to a .txt file within a program, and I am using the following code snippet. I want to output a line of the form:

a(space)b

but I get nothing on the txt file.

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

int main(){

    string a = "string";
    int b = 0;

    fstream f;
    f.open("filename.txt",ios::in | ios::out );
    f << a << ' ' << b << endl;
    f.close();
    return 0;
}
     

CodePudding user response:

If you try this piece of code:

f.open("filename.txt", ios::in | ios::out);
if (!f.is_open()) {
    cout << "error";
}

you will see that the file is never opened. ios::in requires an already existing file (enter image description here


It should work if you should only pass std::ios::out to f.open():

f.open("filename.txt", ios::out);

Read here why you shouldn't be using namespace std;.

CodePudding user response:

Try this version. Few changes:

  1. Include the correct header <string> instead of <cstring>
  2. No using namespace std;
  3. Use std::ofstream for output
  4. No .open(): pass the filename in the constructor
  5. Check if the file is valid after opening
  6. No .close(). Let the destructor do its job.
  7. No std::endl if '\n' is enough.
#include <iostream>
#include <fstream>
#include <string>

int main() 
{
    std::string a = "string";
    int b = 0;

    std::ofstream f("filename.txt");
    if (!f) {
        return EXIT_FAILURE;
    }

    f << a << ' ' << b << '\n';

    return EXIT_SUCCESS;
}
  • Related