Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try to write char[] to a text file

Tags:

c++

iostream

I trying to write a char[256] to a text file. Below is my current work:

         fstream ofs;
         ofs.open("c:\\myURL.txt");
         ofs.write((char*)testDest,256); 
         ofs.close();

It still does not work.

here is the error:

error C2440: 'type cast' : cannot convert from '' to 'char *'

update:

so far, here is my progress attempt, the code can compile, but when running, my program suddenly terminated.

    ofstream stream;
    CBar *a;

    switch(uMessage) {
    case WM_PAINT:
        return bar->OnPaint();
    case WM_ERASEBKGND:
        return 1;
    case WM_LBUTTONDOWN:   //wira
           if (!bar->OnClick(wParam, lParam)) {
        stream.open("C:\\myURL.txt");
        stream << a->testDest << endl;    // if I replace `a->testDest` with "testword" string, my prgrom does not terminated. Why?
        return 0;
        }
        break;
like image 779
karikari Avatar asked Dec 10 '25 22:12

karikari


1 Answers

Several things wrong or "not good" in your code:

  1. You never check if the open fails.
  2. You use clunky write functions.
  3. You don't check if your write is succesful (not quite necessary if you're kind of sure it will work).

This will give you more info if something fails:

#include <fstream>
    using std::ofstream;
#include <iostream>
    using std::cout;
    using std::endl;

int main()
{
    ofstream stream;
    char charArray[] = "Some stuff in a char array.";

    stream.open("C:\\myurl.txt");
    if( !stream )
        cout << "Opening file failed" << endl;
    // use operator<< for clarity
    stream << testDest << endl;
    // test if write was succesful - not *really* necessary
    if( !stream )
        cout << "Write failed" << endl;

    return 0;
}

My guess is that opening the file failed because you lack proper permissions. The above program will tell you where what fails.

UPDATE: To answer your second question: you do this:

CBar* a;

Which creates a pointer but leaves it unitiallized. You then want to dereference it to access its testDest data member, which obviously leads to a crash. You need to initialize your pointer (or don't use a pointer here, I see no reason to):

// Either this
CBar* a = new CBar(/*some arguments, or none, depending on CBar definition*/);
  //...
    cout << a->testDest << endl;

// Or this (better here in my opinion)
CBar a; // OK if there is a default constructor (one with no arguments);
  //...
    cout << a.testDest << endl;

Please read any good tutorial on c++. These are mistakes you make either when you've not slept for three days or if you don't understand the basic concepts of the language.

like image 182
rubenvb Avatar answered Dec 12 '25 10:12

rubenvb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!