hey! i m new and don't know how to read a .dat file in C++. Can anyone help me to put me out of this problem?

A .dat file could be anything. You'll need to know what the file format is. Is it plaintext? Is it binary? Compressed? Encrypted? What structure does it take? Do you have a file format reference?

You can read any file using C++'s conventional file streams. The problem is interpreting what the file stream means.

What Hiroshe said. Also, file name extensions are conventions - they really don't mean anything. You can rename any file with a .zip extension, but that doesn't mean that it is a compressed zip file.

You can do it like ordinary in C.
Try this,

fstream f("yourfile.dat",ios::in);
f.open();
char a[20][20];
for(int i=1;i<=17;i++)
for(int j=1;i<=2;j++)
f>>a[i][j];
f.close();

@ melissad - What you poseted was not c call at all. fstream is from the C++ STL. Not sure if you noticed but your code will run forever or throw an exception for reading outside the bounds of the file or array. There is an error with the inner for loop.

ok Hiroshe actually my file is of numeric type.And there are almost seventeen to eighteen columns but i want to read only first two columns and find the mean of second column. You can see from the file i attached.

Well that is pretty easy to do. You need to calls two >> and one call to ignore to eat the rest of the line. The folwwing is psuedo code:

column1, column2
// use ifstream for file read operations
ifstream file(some data file);
// since the first read operation in a line is >> use that for the loop control
while (file >> column1)
{
    file >> column2
    file ignore rest of line
    add column1 and column2 to some sort of container.
}

You can read here on how to ignore the rest of the line in the file.

commented: Thanks Alot.. +0

if it is a binary file,then u can use read() from the class fstream. if its in text format then the operator >> shoul do fine

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.