Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Problem forming new files and writing on them

0 votes
asked Jun 5 by Tedi Ptv (170 points)

Hello!

So I'm using this online compiler for my easy class problems in c++.

Now I'm solving one, as usual, which requires to open a file and write on it the result.

I'm opening the <fstream> library and I'm opening a file with ofstream d ("a.out"). At this point if i just type d<<"test"; it should create a file and write on it, but it does not. Even if I create the a.out file myself, it doesn't want to write on it.

The real code, that works usually and in this compile doesn't work, is this one:


#include <iostream>

#include <fstream>

using namespace std;

int main(){         /* this piece of code reads some numbers from "a.in" and determinates the length of the longest string of ascending numbers, and writes it down in "a.out" file */

    int max=1,n, a,b, current=1;

    ifstream f ("a.in");
    ofstream d ("a.out");
    f>>n>>a;
    for(int i=2; i<=n;i++){
        f>>b;

        if(a<b)current ++;
        else current = 1;
        a=b;

        if(current > max)max=current;
    }

    cout<<max;

    d<<max;
   

}


It's not running properly on GDB compiler, it prints max on the console and not on the file.

I use Google Chrome to open the compiler, and it worked as a charm for the past 2 years.

1 Answer

+1 vote
answered Jun 9 by Peter Minarik (34,450 points)
Darn, it took me a while to figure out this one.

The problem is that when your code is compiled, the created binary (that is executed when you run the code) is called "a.out".

Then you're trying to create a file called "a.out" and put your max in it, but this file is already in use (you're executing the code for it) so the operating system denies your request to open and write into this file.

Use any other file name than "a.out" and your problem is solved. :)
commented Jun 9 by Tedi Ptv (170 points)
wow! It works!

I can't figure it out how it worked like that until now, and now I need a different file to write on, but as long as it works, everything is ok!

Thank you for your time and for this awesome answer!
commented Jun 10 by Peter Minarik (34,450 points)
My pleasure. :)
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...