3

node.jsのC++アドオン(.cc)ファイルでファイルを作成し、その中にデータを追加する方法を知りたいですか??

以下のコードを使用して同じことを行いましたが、ubuntu マシンでファイル "data.txt" を見つけることができませんでした (その背後にある理由は、コードの下にファイルを作成する正しい方法ではない可能性がありますが、奇妙なエラーを受け取っていません/コンパイル時に警告)。

FILE * pFileTXT;

pFileTXT = fopen ("data.txt","a+");

const char * c = localReq->strResponse.c_str();

fprintf(pFileTXT,c);

fclose (pFileTXT); 
4

1 に答える 1

7

Node.js は、I/O (非同期かどうかに関係なく) を処理する C ライブラリであるlibuvに依存しています。これにより、イベントループを使用できます。

この無料のオンラインブック/ libuv の紹介に興味があるでしょう: http://nikhilm.github.com/uvbook/index.html

具体的には、ファイルの読み取り/書き込み専用の章があります。

int main(int argc, char **argv) {
    // Open the file in write-only and execute the "on_open" callback when it's ready
    uv_fs_open(uv_default_loop(), &open_req, argv[1], O_WRONLY, 0, on_open);

    // Run the event loop.
    uv_run(uv_default_loop());
    return 0;
}

// on_open callback called when the file is opened
void on_open(uv_fs_t *req) {
    if (req->result != -1) {
        // Specify the on_write callback "on_write" as last argument
        uv_fs_write(uv_default_loop(), &write_req, 1, buffer, req->result, -1, on_write);
    }
    else {
        fprintf(stderr, "error opening file: %d\n", req->errorno);
    }
    // Don't forget to cleanup
    uv_fs_req_cleanup(req);
}

void on_write(uv_fs_t *req) {
    uv_fs_req_cleanup(req);
    if (req->result < 0) {
        fprintf(stderr, "Write error: %s\n", uv_strerror(uv_last_error(uv_default_loop())));
    }
    else {
        // Close the handle once you're done with it
        uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL);
    }
}

node.js 用の C++ を作成する場合は、時間をかけて本を読んでください。価値がある。

于 2012-12-07T12:44:37.403 に答える