ismail Vasip
ismail Vasip

Reputation: 1

Ifstream is OK but Ofstream not working in Visual Studio (C++)(WIN11)

When I write a simple ofstream and ifstream instance ,ifstream is working but ofstream is not working. When I run this program ofstream is creating but I don't see output.txt in directory file. I tried turning off COMODO Antivirus but the problem persists. What is preventing me from seeing the output file?

here my First.cpp:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ofstream output("output.txt");
    ifstream input("input.txt");
    if (output.is_open()) {
        cout << "ouput file is open" << endl;
        output << "hi";
    }
    else {
        cout << "output file is not open" << endl;
    }
    int number;
    if (input.is_open()) {
        cout << "input file is open" << endl;
        input >> number;
        cout << "Number:" << number << endl;
    }
    else {
        cout << "input file is not open" << endl;
    }
    input.close();
    output.close();
    return 0;
}

here my input.txt:

21
12
22
23
32

when I run this program:

ouput file is open
input file is open
Number:21

Upvotes: -1

Views: 463

Answers (1)

Andreas
Andreas

Reputation: 36

I see that the issue was related to your Antivirus, but I'll write this anyways for others to read.

When dealing with IO its important to know what directory your executable will execute from. The working directory can be set in the project configuration. Right Click the project > Properties > Configuration Properties > Debugging > Working Directory. Configuration Window

The working directory is also the directory where all your application created files will be generated. For instance the example code generate output.txt at the project working directory.

std::ofstream output("output.txt");
if (!output.is_open())
return -1;

std::cout << "file is open" << std::endl;
output << "Hello there!";
output.flush();
output.close();

project directory screenshot

Upvotes: 0

Related Questions