简体   繁体   English

node.js在C写入时读取txt文件

[英]node.js reading txt file while c writing in it

I want to my node.js function reading from file while c program writing in it at same time if that is not impossible. 我想我的node.js函数从文件中读取,而c程序同时写入它,如果那不是不可能的话。 Node.js function can't read while c writing, I want to remove that lock. 用c编写时无法读取Node.js函数,我想删除该锁。 Also I need to node function doesn't stop until read 'End of file!'. 我还需要节点功能直到读取“文件结束!”才停止。

c program: C程序:

#include <stdio.h>
#include <time.h>
#include <unistd.h>

int main(int argc,char *argv[]) {

    int simulationLength,simulationStep,simulationStepNum,i,time;
    FILE *f;

    if(argc != 3) {
        printf("Bad input!\n");
        return 1;
    }



    simulationLength = atoi(argv[1]);
    simulationStep = atoi(argv[2]);

    simulationStepNum = simulationLength/simulationStep;
    f=fopen("exit.dat","w");

    for(i=0;i<simulationStepNum;i++) {
        time = rand()%10;
        fprintf(f,"TStep %d, Time=%d\n",i,time);
        sleep(time);
        if(i%10 == 0)
            fprintf(f,"Internal error!\n");
    }
    fprintf(f,"End of file!\n");
    fclose(f);
} 

node.js function: node.js函数:

var readline = require('readline');
var fs = require('fs');

module.exports = function() {
    var file = 'app/webmus/app/wemus-cluster-simulation/exit.dat';
    var eof = 'End of file!';  

    var lineReader = readline.createInterface({
        input: fs.createReadStream(file)
    });

    lineReader.on('line', function(line) {
        if (line == eof) lineReader.close();
        console.log(line);
    }).on('close',function(){
        process.exit(0);
    });;   
}  

You can also push changes to file by flushing contents: 您还可以通过刷新内容将更改推送到文件:

for(i=0;i<simulationStepNum;i++) {
    time = rand()%10;
    fprintf(f,"TStep %d, Time=%d\n",i,time);

    // flush data from buffers to disk.
    fflush(f);

    sleep(time);
    if(i%10 == 0)
        fprintf(f,"Internal error!\n");
}

I'm positive, this should resolve your issue. 我很肯定,这应该可以解决您的问题。 Again, if you are on *nix environment, named pipes are best for this kind of work. 同样,如果您在* nix环境中,则命名管道最适合此类工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM