What might be the problem? In this case, the file did not open, because
ios::trunc
only applies to output files.
To find where the error occurred, add some tests of the file status. After every operation, possibly something could have gone wrong. So you need to check.
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
|
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream test;
test.open("test",ios::trunc);
if (test.fail())
{
cout << "Error 1 - could not open input file\n";
return 1;
}
char temp_str[3];
test.getline(temp_str,sizeof(temp_str));
if (test.fail())
{
cout << "Error 2 - getline failed\n";
}
test.seekg(0,test.beg);
if (test.fail())
{
cout << "Error 3 - seekg failed\n";
}
cout << "4 - tellg position: " << test.tellg() << '\n';
}
|
The code as it stands outputs the message:
Error 1 - could not open input file |
I put
return 1
after the error message, if the file is not open, there's no point in continuing with the rest of the program.
So fix that code error now:
|
test.open("test",ios::trunc);
|
should be:
Recompile the code and run the program again.
If the file is still not open now, you need to check the name and location of the input file is correct.
When you get the file to open there may still be errors.
When I run it, this is the output:
Error 2 - getline failed
Error 3 - seekg failed
4 - tellg position: -1 |
Why did the getline fail? Well, the first line of my file is "apple". That needs a buffer big enough to contain the 5 letters plus the null terminator '\0'.
So, let's make the buffer bigger:
becomes
I made the buffer reasonably large, because the line length is often likely to be more than five characters.
Recompile and try again. If all goes well, you should see: