同时写和读 - C

时间:2015-07-08 15:34:22

标签: c

这是一个草图,我想写一个.txt:

time_t timer;
struct tm y2k = { 0 };
int seconds;
int seconds_prev= 0;
int i = 0;
y2k.tm_hour = 0;   y2k.tm_min = 0; y2k.tm_sec = 0;
y2k.tm_year = 100; y2k.tm_mon = 0; y2k.tm_mday = 1;

FILE *f = fopen("file.txt", "w");

if (f == NULL)
{
    printf("Error opening file!\n");
    return 0;
}

for (;;){

    time(&timer);   
    seconds = difftime(timer, mktime(&y2k));

    if (seconds % 2 == 0 && seconds!=seconds_prev) {
        seconds_prev= seconds;
        const char *text = "AAAAAA";
        fprintf(f, "%d-%s\n",i, text);
        fflush(f);
        i++
        if (i == 20){
            break;
        }
    }
}

fclose(f);

此脚本允许在文本文件中每秒写入大约1行。 现在我想读完这个文件,直到它完成。

FILE *file;
size_t nread;

file = fopen("file.txt", "r");
if (file) {
    /*pseudo code*/
    //(reading loop)
    //(some condition that detects the true end of file writing)
    //(buffering information)
    //(end of loop)
    /**************/

    if (ferror(file)) {
        /* deal with error */
    }
    fclose(file);
}

所以主要目标是阅读" file.txt"虽然它一直在写。我面临的一个大问题是,脚本只读取已写入的信息并停止读取。我正在寻找一些条件,旗帜等,让我解决这个问题。到目前为止,没有什么

2 个答案:

答案 0 :(得分:0)

我认为您可以使用命名管道来实现此目的。 nodejs对此无关紧要,因为就你的程序而言,它只是一个普通的文件。

阅读会话

$ mkfifo text.fifo
$ cat text.fifo

foo.c的

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

int main(void)
{
  FILE * f = fopen ("text.fifo", "w");

  for (int i = 0; i < 10; ++i)
  {
    fprintf (f, "Sup %d\n", i);
    fflush (f);
    sleep(1);
  }

  fclose(f);

  return 0;
}

写会话

$ gcc foo.c -std=c99
$ ./a.exe
$

阅读课程

$ mkfifo text.fifo
$ cat text.fifo
Sup 0
Sup 1
Sup 2
Sup 3
Sup 4
Sup 5
Sup 6
Sup 7
Sup 8
Sup 9

$

答案 1 :(得分:0)

我丑陋的最终解决方案:

<强>作家:

for (;;){`

   //printing single chatacters
   char c[25] = "ABCDEFGHIJLMNOPQRSTUVXZ";

    //fprintf(f, "A character: %c\n", c[i]);
    fprintf(f, "-%c", c[i]);
    fflush(f);
    printf("-%c", c[i]);
    i++;
    _sleep(1000);
    if (i == 20){
        break;
    }

    fclose(f); 

<强>阅读器:

file = fopen("file.txt", "r");

if (file) {
    //while (((nread = fread(buf, 1, sizeof buf, file)) > 0)){
    while ((((nread = fread(buf, 1, sizeof buf, file)) >= 0))){
        fwrite(buf, 1, nread, stdout);
        //_sleep(1000);

        int size= sizeof buf;
        for (int i = 0; size; i++){
            if (buf[i] == 'R') { //my [eof]
                out = 1;
                break;
            }
            if (i == 10){//preventing buf[] empty - need improvement
                break;
            }
        }
        if (out== 1) break;
    }
    if (ferror(file)) {
        printf("Bad. \n");
    }
    fclose(file);
}

效率不高但工作正常。

相关问题