Re: problems with pointers (i think)
"Darren" <foo.bar@world.com> wrote...[color=blue]
> i'm trying to write some code to generate seperate files with the name of[/color]
a[color=blue]
> call number, and containing the call data, from one big file containing[/color]
all[color=blue]
> data.
>
> but when i run it, i get the individual files created, but just containing
> "NOTF: 206791552" and not the data. the right call number is inside the
> corresponding file, just no data. i am at a loss - please help!
>
> each call terminiates with a '~'.
>
> #include <iostream>
> #include <fstream>
>
> using namespace std;
>
> int main ()
> {
> int length;
>
> char * buffer;
> char call_num[12];
> char fname[13];
>
> int i = 0;
> int j = 0;
> int k = 0;
> int l = 0;
>
>
> ifstream inputfile ("data.txt");
> if (! inputfile.is_open())
> { cout << "Error opening file: data.txt does not exist."; exit (1); }
>
> // get length of file:
> inputfile.seekg (0, ios::end);
> length = inputfile.tellg();
> inputfile.seekg (0, ios::beg);
>
> // allocate memory:
> buffer = new char [length];
>
> // read data as a block:
> inputfile.read (buffer,length);
>
> inputfile.close();
>
> for (i=0; i < length; i++)
> {
> if ( (*(buffer+i)=='N') && (*(buffer+(i+1))=='O') &&
> (*(buffer+(i+2))=='T') && (*(buffer+(i+3))=='F') )
> {
>
> for (k=0; k < 9; k++)
> {
> call_num[k] = (* (buffer+ (i+(6+k)) ) );
> l++;
> }
>
> call_num[9] = '.';
> call_num[10] = 't';
> call_num[11] = 'x';
> call_num[12] = 't';[/color]
'call_num' array contains only 12 characters. Indices range
from 0 to 11. Attempting to index beyond the last number causes
undefined behaviour. You should probably rethink the size of
the 'call_num' (like make it 14). And don't forget to initialise
it to all zeroes or set call_num[13] to 0 here.
[color=blue]
>
> sprintf( fname, call_num);[/color]
Why do you need to do this 'sprintf' nonsense? Couldn't you just
construct the 'fname' in place?
It is very likely that since 'call_num' does not contain null char
at the end, 'sprintf' also attempts to write beyond the end of the
'fname' array, causing undefined behaviour.
Two wrongs (undefined behaviours) will never make it right.
[color=blue]
> ofstream outFile (fname);
>
> while (*(buffer+(i+1)) != '~')
> {
> outFile << buffer[i];
> i++;
> }
>
> cout << "Creating file: ";
> cout.write (call_num,13);
> cout << endl;
> j++;
> }
>
>
> }
>
> cout << endl << "Total number of files created = " << j << endl;
>
> return 0;
> }
>
>[/color] |