Can not get file to open!

I am tasked with creating a program that collects data from a text file concerning postage stamps and I cannot seem to open the input file for the life of me. The file exists. What's up?!

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
41
42
43
44
  #include <iostream>
#include <string>
#include <fstream>
#include <iomanip>

using namespace std;

//class definition
class stampclass
{
    public:

    string country;
    int quantity;
    string condition;
    int year;
};


int main()
{
    fstream inFile;
    inFile.open("stamps.txt");

    if(inFile.fail())
    {
        cout << "The input file could not be opened.";
    }
    else
    {


        stampclass stamp[10];

        while(inFile >> stamp[0].country >> stamp[1].quantity >> stamp[1].condition >> stamp[1].year)
            {

            }


        cout << stamp[0].country << endl;
    }
}
Try including the full path in the file name and the name is correct, and of course that the file even exists.
Hello WakelessFoil,

Where is the input located, (full path)?

Where is the file for the above code located, (full path)?

Do you use an IDE, if so which one?

I need to test some code I am thinking of in the mean time.

Andy
Hello WakelessFoil,

Give this a try.

Comment your if statement, (all lines), and add this to your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
if (!inFile)
{
    cout << "\n     The input file could not be opened.\n\n";

    DWORD errorMessageID = GetLastError();

    LPSTR messageBuffer = nullptr;
    size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
                                    NULL, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&messageBuffer, 0, NULL);

    std::string message(messageBuffer, size);

    std::cout << "\n  " << message << '\n';

    return 1;
}

Sorry this will only work with a Windows operating system. You will also have to add the header file <Windows.h> at the end of your "#includes".

If this does not work you will need to figure out what is considered the current working directory to use when you run your program.

Andy
Hello WakelessFoil,

When I went further into the program I realized I do not have the input file that you are using. And anything I come up with may not be the same as what you have.

When posting code and a question that uses an input file post the input file so everyone can use the same information. It really helps to eliminate the guess work.

I was looking at your while loop and see some problems:
1
2
3
4
5
6
while (inFile >> stamp[0].country >> stamp[1].quantity >> stamp[1].condition >> stamp[1].year)
{
    ;  // <--- An empty while loop should contain the (;) as a start.
    // Why are you storing "country" in element (0) and "quantity", condition" and "year" in element (1)
    // Also if the input file has 100 records, all are going int element (0) and element (1).
}

When accessing the array you should use a variable and not a constant number. As is everything that you read from the file is going into the same elements of the array. Not what you want.

Since you are doing the read in the while condition you should add a limit as to how much to read. Such as:
 
while (idx < MAXRECORDS && inFile >> stamp[idx].country >> stamp[idx].quantity >> stamp[idx].condition >> stamp[idx++].year)
This is untested at the moment until I have a file to work with.

constexpr int MAXRECORDS{10};

Andy
Try opening using:

 
ifstream inFile;


Maybe the file is read-only - as fstream opens for in/out.

Also note that you don't need the open statement. You can do this:

 
ifstream inFile("stampts.txt");

Hello,

Here is some more context and information on the project.

The input file details 10 stamps with variables country, quantity, condition, and year.

INPUT FILE:
1
2
3
4
5
6
7
8
9
10
China	20	new	2004
France	30	used	2000
Brazil	10	used	2007	
Cuba    50	new	1999
Greece	17	used	2001
Japan	25	new	1980
Norway	40	new	2011
Russa	33	used	1988
Spain	11	used	2001
Canada	13	used	2015


I am supposed to input this table and output it to the terminal sorted by year.
Also I was using different array addresses just to test to see if I was reading in correct information. As arrays start at zero I was going to start at [0].
The inFile is in the same folder as the main.cpp and main.cbp files. Usually this works for me.
Last edited on
Using a vector rather than an array:

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

struct Stamp {
	std::string country;
	int quantity {};
	std::string condition;
	int year {};
};

std::istream& operator>>(std::istream& is, Stamp& s)
{
	return is >> s.country >> s.quantity >> s.condition >> s.year;
}

std::ostream& operator<<(std::ostream& os, const Stamp& s)
{
	return os << s.country << '\t' << s.quantity << '\t' << s.condition << '\t' << s.year;
}

int main()
{
	std::ifstream ifs("stamps.txt");

	if (!ifs.is_open())
		return (std::cout << "Cannot open inputfile\n"), 1;

	std::vector<Stamp> stamps;

	for (Stamp s; ifs >> s; stamps.push_back(s));

	std::sort(stamps.begin(), stamps.end(), [](auto s1, auto s2) {return s1.year < s2.year; });

	for (const auto& s : stamps)
		std::cout << s << '\n';
}


which displays:


Japan   25      new     1980
Russa   33      used    1988
Cuba    50      new     1999
France  30      used    2000
Greece  17      used    2001
Spain   11      used    2001
China   20      new     2004
Brazil  10      used    2007
Norway  40      new     2011
Canada  13      used    2015


If you don't want to use vector but a c-style array, then consider:

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
41
42
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>

struct Stamp {
	std::string country;
	int quantity {};
	std::string condition;
	int year {};
};

std::istream& operator>>(std::istream& is, Stamp& s)
{
	return is >> s.country >> s.quantity >> s.condition >> s.year;
}

std::ostream& operator<<(std::ostream& os, const Stamp& s)
{
	return os << s.country << '\t' << s.quantity << '\t' << s.condition << '\t' << s.year;
}

int main()
{
	const int maxStamp {20};

	std::ifstream ifs("stamps.txt");

	if (!ifs.is_open())
		return (std::cout << "Cannot open input file\n"), 1;

	Stamp stamps[maxStamp] {};
	size_t nostmp {};

	for (Stamp s; nostmp < maxStamp && ifs >> s; stamps[nostmp++] = s);

	std::sort(stamps, stamps + nostmp, [](auto s1, auto s2) {return s1.year < s2.year; });

	for (size_t s = 0; s < nostmp; ++s)
		std::cout << stamps[s] << '\n';
}

Thank you for helping me work and develop a more streamlined script. Unfortunately even with the revised code, it still wont read from the input file. I have the stamps.txt located in my folder with all the other project files. I am not sure what is going on with code blocks.
What os are you using?

What is the full exact path to the file?

Are you running the program from a command prompt or from within the IDE?

If from a command prompt, can you type the file to display in the command prompt?
I am using windows 10.

the file path is C:\Users\lucke\Desktop\ass 9 test\stamps.txt

The program runs in command prompt when I press the build and run button.

I cannot type anything as the program ends and closes the terminal windows with the press of any key.
With Windows there are two ways to get a command prompt that won't close when running your program ends.

1. Windows Key -> type "cmd" (without the quotes) -> hit "Enter"

2. In File Explorer click the address bar so the entire address is highlighted -> type "cmd" (without the quotes) -> hit "Enter"

Drag and drop your program file into the command prompt, that pastes the program's location into the window. Hit "Enter"

The command prompt won't close when your program ends.

If'n your program does any file access I recommend using File Explorer to navigate to where your program's executable is located and run the command prompt from there (method 2). The file(s) you want to muck around with should be located there as well.

Or you start a command prompt where your file(s) are.

You can open a command prompt and use DOS commands to change the location. I prefer using the File Explorer method vs. using DOS commands to change where the prompt is located.

Running your program within an IDE such as Visual Studio or Code::Blocks will run a command prompt window that will stay open after your program ends, until you "hit a key."

Using an IDE is the easiest method IMO, less mucking around with DOS commands, etc.
Try
 
std::ifstream ifs("C:\\Users\\lucke\\Desktop\\ass 9 test\\stamps.txt");

Hello WakelessFoil,

I still think that the "stamps.txt" file is in the wrong directory.

I did not see an answer to my question, so I will ask differently.

What it the full path to the ".cpp" file that contains the "main" function?

When I created a solution in Code::Blocks the program ran fine. Even the if statement I showed you works. And when it can not find the file the output is:

     The input file "stamps1.txt" could not be opened.


  The system cannot find the file specified.


Process returned 1 (0x1)   execution time : 3.898 s
Press any key to continue.

With the proper file name I get this output:



10 lines read from file.

 Country: China
 Quantity: 20
 Condition: new
 Year: 2004

 Country: France
 Quantity: 30
 Condition: used
 Year: 2000

 Country: Brazil
 Quantity: 10
 Condition: used
 Year: 2007

 Country: Cuba
 Quantity: 50
 Condition: new
 Year: 1999

 Country: Greece
 Quantity: 17
 Condition: used
 Year: 2001

 Country: Japan
 Quantity: 25
 Condition: new
 Year: 1980

 Country: Norway
 Quantity: 40
 Condition: new
 Year: 2011

 Country: Russa
 Quantity: 33
 Condition: used
 Year: 1988

 Country: Spain
 Quantity: 11
 Condition: used
 Year: 2001

 Country: Canada
 Quantity: 13
 Condition: used
 Year: 2015

Process returned 0 (0x0)   execution time : 0.214 s
Press any key to continue.


The first line is to let me know how many lines were read from the file. You do not need this other than for testing.

When I added the file "stamps.txt" to the project I used the button "New file", for me it is the first button on the first line of tools, and then choose "Empty file". After that I just followed the instructions and at some point had to change the extension from "cpp" to "txt. This put the file where it needs to be without having to search for the correct directory.

Andy
I feel stupid. I believe that the reason it could not find the file is because I named it "stamps.txt" instead of just "stamps". So the file was effectively named "stamps.txt.txt and it couldn't find it. Sometimes it the simplest things.

Thank all who helped!

-J
Hello WakelessFoil,

I was thinking it was a file name problem if it was not stored in the correct directory.

Andy
Suggest you change Explorer settings so that it doesn't 'hide' extensions but always shows them.
Topic archived. No new replies allowed.