I/O file - am i following the direction?

• Prompt the user for an input file and an output file.

- The input file must be a valid text file and exist. If an invalid file name is entered the
user should be continuously prompted until a valid file is enters.

- The output file must have a different name then the input file and if existed before will
be over written.


Am if following the direction correctly? Feel like something is missing.


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
29
30
31
32
33
34
35
36
  #include <iostream>
#include <fstream>
#include <iomanip>
#include <string>

using namespace std;

const int MAXSIZE = 80;
char * returnfilename(char* );

int main(void)
{
  char * filename = new char [MAXSIZE];
  filename = returnfilename(filename);

  // more codes

  return 0;
}

char * returnfilename(char * fn)
{
  ifstream myfile;
  cout<<"Please enter a valid file name: ";
  cin>> fn;

  myfile.open(fn);
  while(!myfile.is_open())
  {
    cout<<" Invalid file name, please re-enter ";
    cin >> fn;
    myfile.open(fn);

    return fn;
  }
}



This is what it supposed to display.
==========================================

Please Enter an valid File Name: word.txt

Please Enter an output File Name: word.out

===========================================
Last edited on
1.) You have included C++ strings, use them?

2.) You did not delete why you new'd

3.) Consider a small function like this to test a valid file:

1
2
3
4
5
6
bool ValidFile(const std::string f)
{
    std::ifstream ifs(f.c_str());
    if(ifs) return 1;
    else return 0;
}


4.) The way you are getting the valid filename from that function seems a little strange to me, perhaps try using your main thread of execution more?

1
2
3
4
5
6
7
8
9
10
11
12
{
    std::string file_in;
    bool Valid = 0;
    do
    {
        std::cout << "Enter the file name to open: ";
        std::cin >> file_in;
        if(ValidFile(file_in)) Valid = 1;
        else std::cout << "invalid file!\n";
    }
    while(!valid);
}


EDIT:

5.) Or use code as stated in 4.) to return a valid std::string.
Last edited on
Perfect. If i enter an invalid file name it finally loops until i enter a right name. Thanks a lot.
Very welcome, glad to help. :]
Topic archived. No new replies allowed.