尝试将char []写入文本文件

kar*_*ari 0 c++ iostream

我试图将char [256]写入文本文件.以下是我目前的工作:

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

它仍然无法正常工作.

这是错误:

错误C2440:'type cast':无法从''转换为'char*'

更新:

到目前为止,这是我的进度尝试,代码可以编译,但在运行时,我的程序突然终止.

    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;
Run Code Online (Sandbox Code Playgroud)

Bal*_*arq 6

你需要传递给fstream,在open()中,你期望做的那种操作:输入,输出,甚至两者兼而有之.你应该尝试:

ofs.open( "c:\\myURL.txt", ios::out | ios::text);
Run Code Online (Sandbox Code Playgroud)

无论如何,使用ofstream而不是通用fstream会更好:

 ofstream ofs;
 ofs.open( "c:\\myURL.txt", ios::text );
 ofs.write( (char*)testDest, 256 );    
 ofs.close();
Run Code Online (Sandbox Code Playgroud)


rub*_*nvb 6

你的代码中有些错误或"不好":

  1. 你永远不会检查是否open失败.
  2. 你使用笨重的write功能.
  3. 你不会检查你的写作是否成功(如果你确定它会起作用,那就不是很必要了).

如果出现问题,这将为您提供更多信息:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我的猜测是打开文件失败,因为你没有适当的权限.上述程序将告诉您哪里失败了.

更新:回答你的第二个问题:你这样做:

CBar* a;
Run Code Online (Sandbox Code Playgroud)

这会创建一个指针,但会使其保持单一化.然后,您希望取消引用它以访问其testDest数据成员,这显然会导致崩溃.你需要初始化你的指针(或者不要在这里使用指针,我没有理由):

// 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;
Run Code Online (Sandbox Code Playgroud)

请阅读有关c ++的任何优秀教程.当你没有睡三天或者你不理解语言的基本概念时,这些都是你犯的错误.

  • 什么是"笨重的写功能"? (2认同)