Opening a txt file within a function

Hello all, Im having some trouble figuring out how to correctly open a txt file within a function.

I understand I need to use ifstream input.file(), but im confused on where to add it. Would I put it in my main, or within my actual function.

Thanks to all with any advice.


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
 
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int countCharacters(string file);

int main(){
countCharacters("Bradbury1.txt");
return 0;
} // end of main 

int countCharacters(string file){
 

int numOfchars = file.length();
for (unsigned int i = 0; i < file.length(); i++){
  if (file.at(i) == ' '){
    numOfchars--;
  }
  cout << "Number of Characters: " << numOfchars << endl;
}

}
Hello liam401,


Would I put it in my main, or within my actual function.


Either one would work. It really depends on where you would need to use the file stream and how long you need to keep the defined file stream around.

If it is just used in the function I would setup and open the file stream in the function. And when the function looses scope the stream will close and the variable will be destroyed.

If you setup the "ifstream" in "main" then you will have to pass it to the function and pass by reference.

Andy
file is a string *representing* the NAME of the file.
it is not a file.
a file is of type fstream, or ifstream (input) or ofstream(output).
eg
ifstream reallyafile(file); //attempts to open 'file'
or
ifstream reallyafile;
reallyafile.open("something.txt");
...
see full examples on this site in the reference.
Open (and close) the file in your function if your function is to read the file.

Or in main.

What you currently are doing in the function is counting the number of non-space characters in the file name, not in the actual file.

This counts the number of alphabetic characters in the file and the number of spaces:
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
#include <iostream>
#include <fstream>

int main()
{
   std::ifstream  fin("text.txt");

   if (fin)  // was the file opened successfully?
   {
      int char_count { };
      int space_count { };

      while (fin)
      {
         char ch { };
         fin.get(ch);

         if ((ch > '@' && ch < '[') || (ch > '`' && ch < '{'))
         {
            char_count++;
         }
         else if (ch == ' ')
         {
            space_count++;
         }
      }

      std::cout << "# of characters in the file : " << char_count << '\n';
      std::cout << "Spaces in the file          : " << space_count << '\n';
   }
}

With the following text file:
Hello World
Welcome to CPlusPlus
Goodbye World

The output will be:
# of characters in the file : 40
Spaces in the file          : 4

Doing it in a function:
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 <iostream>
#include <fstream>
#include <string>

void CountFile(std::string, int&, int&);

int main()
{
   int char_count { };
   int space_count { };

   CountFile("text.txt", char_count, space_count);

   std::cout << "# of characters in the file : " << char_count << '\n';
   std::cout << "Spaces in the file          : " << space_count << '\n';
}

void CountFile(std::string filename, int& ch_cnt, int& sp_cnt)
{
   std::ifstream  fin(filename);

   if (fin)  // was the file opened successfully?
   {
      while (fin)
      {
         char ch { };
         fin.get(ch);

         if ((ch > '@' && ch < '[') || (ch > '`' && ch < '{'))
         {
            ch_cnt++;
         }
         else if (ch == ' ')
         {
            sp_cnt++;
         }
      }

   }
}
Without a function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <fstream>
#include <cctype>

int main()
{
	std::ifstream fin("text1.txt");

	if (fin.is_open()) {
		int alpha_cnt { };
		int space_cnt { };

		for (char ch {}; fin.get(ch); ) {
			alpha_cnt += std::isalpha(ch);
			space_cnt += (ch == ' ');
		}

		std::cout << "# of alpha chars in the file : " << alpha_cnt << '\n';
		std::cout << "spaces in the file           : " << space_cnt << '\n';
	} else
		std::cout << "Cannot open file\n";
}


With a function with the file opened in main (C++17):

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
#include <iostream>
#include <fstream>
#include <cctype>
#include <utility>

auto fileCnt(std::istream& is)
{
	int alpha_cnt { };
	int space_cnt { };

	for (char ch {}; is.get(ch); ) {
		alpha_cnt += std::isalpha(ch);
		space_cnt += (ch == ' ');
	}

	return std::pair(alpha_cnt, space_cnt);
}

int main()
{
	std::ifstream fin("text1.txt");

	if (fin.is_open()) {
		const auto [alpha, space] {fileCnt(fin)};

		std::cout << "# of alpha chars in the file : " << alpha << '\n';
		std::cout << "spaces in the file           : " << space << '\n';
	} else
		std::cout << "Cannot open file\n";
}


With a function with the file opened in the function (C++17):

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
#include <iostream>
#include <fstream>
#include <cctype>
#include <utility>
#include <string>
#include <optional>

auto fileCnt(const std::string& fnam)
{
	std::ifstream ifs(fnam);

	if (ifs.is_open()) {
		int alpha_cnt { };
		int space_cnt { };

		for (char ch {}; ifs.get(ch); ) {
			alpha_cnt += std::isalpha(ch);
			space_cnt += (ch == ' ');
		}
		return std::optional {std::pair(alpha_cnt, space_cnt)};
	}

	return std::optional<std::pair<int, int>> {std::nullopt};
}

int main()
{
	if (const auto cnts = fileCnt("text1.txt"); cnts) {
		std::cout << "# of alpha chars in the file : " << cnts->first << '\n';
		std::cout << "spaces in the file           : " << cnts->second << '\n';
	} else
		std::cout << "Cannot open file\n";
}


Last edited on
Topic archived. No new replies allowed.