Adding .txt IF the filename isnt "filename.txt" already

Hello people!

I've been stuck on this assignment for a few days now and even though i've found some helping threads that handles basicly the same subject i haven't been able to find quite what im looking for, so i've decided to ask for help. :)

What i need to do is to write a function where the user can type in a filename, this will open the file, however, im also supposed to check the filename for ".txt" or ".TxT" (or other variations), if ".txt" is found, the program will read the file, otherwise it will append ".txt" to the filename and then read the file.

I already know how to open the file, what i need help with is really the if-statement that searches for .txt and if it isnt found, it will add .txt to the filename. My teacher recommended using .rfind() and .append(), but i cant figure out how to write a good if-statement.

this is what i've got so far :

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
37
38
39
40
#include <string>
#include <cctype>
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib> 

using namespace std;
  
int main()
{
  string txt = ".txt";
  string filename;
  cout << "Ange filename: ";
  getline( cin, filename );
  filename.length();

  ifstream fin( filename.c_str() );


  str.append(txt);     



  if ( !fin )//this is the if-statement i would like to change to a loop(?) that
    {        //searches for .txt and if it isnt found ".txt" should be added.
      cout << "Filen kunde inte öppnas"
           << endl;
      exit( EXIT_FAILURE );
    }


    char c;
  while ( fin.get(c) )
    {
          cout << c;
    }

  return 0;
 }


Hope someone can help, thanks in advance!
This statement

filename.length();

has no sense because it does nothing. Other statements also do not do what you want.

If you entered a file name you should check whether it is ended with ".txt" or ".TXT" or even with ".TxT". How to do this? You should find the last occurence of the period "." and check whether after it there are letters "txt". This can be done with member function rfind as your teacher said.

For example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const char *default_ext = ".txt";
bool ext_is_present = false;

std::string::size_type pos1;

if ( ( pos1 = filename.rfind( '.' ) ) != std::string::npos )
{
	for ( std::string::size_type i = pos1 + 1; i != filename.size(); i++ )
	{
		filename[i] = std::tolower( filename[i] );
	}

	if ( filename.compare( pos1, std::string::npos, default_ext ) == 0 )
	{
		ext_is_present = true;
	}
	else
	{
		filename.erase( pos1 );
	}
}

if ( !ext_is_present ) filename += default_ext;

Last edited on
Thanks alot Vlad, much appreciated!
Topic archived. No new replies allowed.