Hi,
I've been working on this code but recently there's been a problem with a section of my code, this being that there was a stack overload but now, the code just stays in a loop saying that there is an invald arguement. I don't know how to get it to finish and open the file to write to it.
Any help would be appreciated!
This is the code:

void writefile()
{
	char writefile[1000000];
	
	char openfile [20];
	
         FILE * pFile;
	
         cout << "\nFile name to open: ";
	cin >> openfile;
	
         pFile = fopen (openfile ,"w");

                   if (pFile == NULL) perror ("Error opening file");
		 else {
	
         cout<<"Enter text:"<<endl;
	cin>>writefile;

	fputs(writefile, pFile);
	fclose (pFile);
}
}

Recommended Answers

All 7 Replies

So .. where is the problem ?

The problm is that when text is entered, it immediately says that there is an error and goes into an infinite loop which i dont know how to stop it, aswell as not saving the text entered

You posted code that doesn't contain a loop.

oh well i figured it had something to do with the if statement but I dont know if theres anything wrong with it

I tried the code below and it worked.

#include <iostream>
#include <cstdio>

using namespace std;

void writefile()
{
	char writefile[1000000];
	
	char openfile [20];
	
         FILE * pFile;
	
         cout << "\nFile name to open: ";
	 cin.getline(openfile, 20);
	
         pFile = fopen (openfile ,"w");

                   if (pFile == NULL) perror ("Error opening file");
		 else {
	
        cout<<"Enter text->";
	cin.getline(writefile, 1000000);

	fputs(writefile, pFile);
	fclose (pFile);
}
}

int main()
{
  writefile();
  return 0;
}

Two problems with the code. An immediate and major one is that

char writefile[1000000];

attempt to allocate one million characters (that is one megabyte) on the stack. The stack is a very limited resource. For example, Windows by default gives one megabyte for the whole stack, and by the time your function is called part of it is already in use. No wonders you have a stack overflow. Never ever allocate large objects in automatic storage.

Problem number two is

void writefile()
{
	char writefile[1000000];

Giving a function and a variable same names may or may not cause a headache to a compiler. It certainly causes one to a reviewer.

> I tried the code below and it worked.

This is probably the most unprofessional way to answer the question.

Than you, that was really helpful in explaining what was wrong. When I change the size of the array now and change the name I get an assertion error expression:(stream!=NULL) and so I dont know what to do with that either

but thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.