Fraser Ross said:
#include <fstream>
#pragma hdrstop
#include <condefs.h>
#pragma argsused
int main(int argc, char* argv[])
{
std::fstream I;
I.open("C:\\File.ext");
if (I.is_open()) {
unsigned short a;
I >> a;
return 0;
}
else
return 1;
}
Is there anything wrong with this?
I wouldn't use an fstream to just read text. I tried
your program, and it read from a text file with ASCII
representations of numbers in it, but it also corrupted
the file, adding '3's to the beginning.
Use an ifstream instead.
Why does the reading function fail?
Probably because the file you're trying to open and
read from either doesn't exist, or it doesn't contain
ASCII representations of short integers separated by
white spaces.
Here's an improved version of your program:
// ======= C:\test.txt =======
34 92 61485 2 817
// ======= inserter-test.cpp =======
#include <iostream>
#include <fstream>
using std::ios_base;
using std::cout;
using std::cerr;
using std::endl;
using std::ifstream;
int main()
{
ifstream I ("C:\\test.txt");
if (!I.good() || !I.is_open())
{
cerr << "Error: Couldn't open file!" << endl;
exit(666);
}
unsigned short int a = 0;
while (1)
{
I >> a;
if (I.bad())
{
cerr << "Error: Input bad!" << endl;
I.close();
exit(666);
}
else if (I.eof())
{
cout << "End of file." << endl;
break;
}
else if (I.fail())
{
cerr << "Error: Input fail!" << endl;
I.close();
exit(666);
}
else
{
cout << "Number is: " << a << endl;
}
}
I.close();
return 0;
}
// ======= RESULTS: =======
wd=C:\C\test
%inserter-test
Number is: 34
Number is: 92
Number is: 61485
Number is: 2
Number is: 817
End of file.
--
Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant