Opening/creating files

I've already written a good size program, for a slight beginner.
Part of what I've done, is that it will look to see if my file "Namefile.txt" is open, if it is and it isnt at eof, it will extract the name within the txt and import it into a sentence. "Welcome back, *name*."

It works just like I want it to, if the text document is already created.
I'm trying and failing on initially creating the file, if it doesnt exist but skipping to the rest of my code if it does exist.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  
  string name;
  ifstream ifName;
  ofstream noName;
  ifName.open ("Namefile.txt");

if (ifName.is_open())
{
	ifName >> name;
  if (!ifName.eof())
  {
    ifName >> name;
    cout << "Welcome back, " << name << "." << endl;
    ifName.close();
  }
  else if(ifName.eof())
  {
    ifName.close();
	noName.open("Namefile.txt", ios::app);
    cout << "Please enter your name: ";
    getline (cin, name);
	noName << name << endl;
    noName.close();
  }
  else
	cout << "Cannot open file." << endl;
}

That is the section that I'm working on.

I've found that when I use, noName.open();, it creates the text file named Namefile, as I desire.
But, if I add the, noName.open();, before the, ifName.open();, it will ask for a name every compile, no matter if I leave the noName open or if I close it before or after the, ifName, is opened.

If I'm a bit confusing, sorry.

Again, the code that I showed above works perfectly; IF the text document is already created. im trying to create the file before the already shown code so that the shown code will work without having to initially manually create the Namefile text document. lol

Any help would be much appreciated! Thank you.
When you "create" the file, open it in append mode so if the file already exists, you don't wipe the contents.
Tru, I just want to make certain that i understand.
you want the code to check for the existence of the file (NameFile.txt)

IF it does exist, then do the code in the example,
i.e. open the file in append mode
ELSE
ask the user for the name or maybe location
create the file in write mode
and continue on...


btw, this 'new' code will be placed before line 5.

= = = = = =

egkenny October 6, 2004 at 18:03:15 Pacific
The trick is to use the ios flags. Make sure you reset any error flags after you test them. The following program will only write to a file if it does not exist.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
ifstream inp;
ofstream out;
string myFileName;
myFileName = "mydata.txt";
inp.open(myFileName.c_str(), ifstream::in);
inp.close();
if(inp.fail())
{
inp.clear(ios::failbit);
cout << "Writing to file..." << myFileName.c_str() << endl;
out.open(myFileName.c_str(), ofstream::out);
out << "Hello World" << endl;
out.close();
}
else
{
cout << "Error...file """ << myFileName.c_str() << """ exists" << endl;
}
return 0;
}


btw, this code ripped off ... er, on loan from some one named EgKenny
I got it to work. If the file doesn't exist, it will skip to noName.open("Namefile.txt"); , then a goto loop back to the top, it will notice the the file exists now, see the file is at eof and ask for a name, save name into file and then loop back to the top again. Finally, it will look into the file, see that it isn't at eof and input the name from the file into the program.

Opening up the file in append mode stopped it from asking for a name, asking again, asking again.. so on every time the program started.

Now, I'm just trying to find out how to clear my screen without the evil system, and since im using C::B.. i guess C::Bs hates clrscr(), so no clrscr().
Add I'd rather not spam the console with blank lines for it to reset if possible.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <fstream>
#include <string>
#include <iostream>

int main()
{
     // This won't create a file unless you use ios::app or ios::trunc.
     std::fstream f("Namefile.txt", std::ios::in | std::ios::out | std::ios::app ) ;

     if (!f) 
     {
	 std::cerr << "Unable to open file.\n" ;
	 return 1 ;
     }


     std::string name ;
     if ( f >> name )
		 std::cout << "Welcome back, " << name << ".\n";
     else
     {
          f.clear() ;

          std::cout << "Please enter your name: ";
          std::getline(std::cin, name);
	  f << name ;
     }   
}
Last edited on
*Program starts*
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
      cout << "program loading..." << endl;
      cout << "Searching for 'Namefile.txt..." << endl;
loop:  
  if (file exists) 
  {
      cout << "File located." << endl;
  *Open file*
  if (!file.eof)
      cout << "Welcome back, " << name << ".\n\n";
  else if (file.eof)
    {
      cout << "Please enter your name: ";
        getline (cin, name);
        noName << name << endl;
      cout << "Name saved." << endl;
    }
  else
      cout << "Unable to open file." << endl;
  }
  else (file doesn't exist)
      {
      cout << "File could not be located." << endl;
    *Create file*
      cout << "\nFile created." << endl;
    *Clear screen* //Currently using 'system("cls");' until I can find a better function 
                           //that works with Code::Blocks and doesn't take up 50 lines.
    goto loop;
      }

This was a quick draft written in the reply box describing what I want to do.
1. Check if file exists.
2a. If it exits, read file.
3a. If file isn't at eof, extract content (name) from file and input it.
3b. If file is at eof, ask for name, save name to file. clear screen & goto check again
3c. file couldn't be opened, error.

2b. if it doesnt exit, create file. clear screen & goto check again

@cire, your example works. I just would like to have my program provide a little feedback/information to the user, so that it isn't a "it just does it" feeling.
I can be a little over complicated at times, I know.

The only issue that I think I have with this setup is having it actually check if the file exists. Because if I do fstream or ofstream at the beginning, it just creates it. How can I actually "check" whether or not the file exists and use it for an if else.
Topic archived. No new replies allowed.