-
reading files
i want to open a wav file but it does not work this way. why?
#include<fstream.h>
void main()
{
unsigned long x;
ifstream file1("sourcepathstring");
ofstream file2("targetpathstring");
while(!file1.eof())
{
file1>>x;
cout<<x<<endl;
file2<<x<<endl;
}
file1.close();
file2.close();
}
it is not working this way? why?
if i have char instead of unsigned long it runs when i convert from
char to ASCII number, but this way i am loosing data, also i want
to know WHY it is not working.
thanks
-
sorry, this is the correct prog.
#include<fstream.h>
void main()
{
unsigned long x;
ifstream file1("sourcepathstring",ios::binary);
ofstream file2("targetpathstring",ios::binary);
while(!file1.eof())
{
file1>>x;
cout<<x<<endl;
file2<<x<<endl;
}
file1.close();
file2.close();
}
-
sorry again :)
when i say it is not working i mean that i have only "0" in the
screen.
-
If you want to read and write binary files you should use the read and write member functions -
Code:
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
unsigned long x;
ifstream file1("sourcepathstring",ios::binary);
ofstream file2("targetpathstring",ios::binary);
while(!file1.eof())
{
file1.read((char*)&x,sizeof(x));
cout << x<<endl;
file2.write((char*)&x,sizeof(x));
}
file1.close();
file2.close();
return 0;
}
-
Thanks a lot. :)
it worked, i did not use the std but it worked :)
can you explain to me why the pointer to a char is needed
in the read and write member function?
x is a number, not a character...shouldn't it be
file1.read((unsigned long*)&x,sizeof(x));
??
-
The write and read member functions take a pointer to a char (byte sized variable). Unless you explicitly cast your buffer to a char*, it won't compile. It will then read/write the amount bytes into your buffer that you specify in the second parameter, which in your case is the sizeof a long.
You wouldn't ever have to do (unsigned long*)&x, if x was an unsigned long, just &x would be sufficient otherwise you are casting a pointer to the type it already is. It would be like doing
this -
int a =10;
(int)a=20; //unecessary a is already an int
-
-
Here's one way.
Code:
#include<stdio.h>
#include<fstream.h>
int main()
{
unsigned long x;
remove("targetpathstring");
ifstream file1("sourcepathstring",ios::binary);
ofstream file2("targetstring",ios::binary);
while(!file1.eof())
{
file1.read( (unsigned char *) &x,sizeof(unsigned long));
file2.write( (unsigned char *) &x,file1.gcount());
}
file1.close();
file2.close();
return 0;
}