gpt4 book ai didi

c - 如何编写监视文本文件中新数据的程序

转载 作者:行者123 更新时间:2023-11-30 17:38:28 26 4
gpt4 key购买 nike

我有一个程序,代码如下,它监视一个文本文件并逐行获取数据并将输出打印到另一个文件。

当程序运行时,并非所有数据都会出现在文件中。文本文件将在几天内写入。

我需要能够模拟程序写入文本输入文件。我该怎么做?

我在 Windows 7 上运行,为了测试这一点,我运行了以下命令行:

类型 CON>input.txt

但是当我运行代码时, is null ,因此代码立即返回。我怎样才能解决这个问题,以便代码正确打开文件。我还需要它继续“轮询”(不确定这是否是正确的术语),直到它看到“e”字符作为该行的第一个字符,然后才能关闭。

我使用参数运行程序:myprog.exe input.txt output.txt

这是代码:

/* Prints ranges of numbers in format n number1 number2 where character n
indicates 2 numbers to follow. print from n1+1 to n2. e indicates end
of numbers to process.
*/
#include <stdio.h>

int main(int argc, char* argv[]) {
char s[100];
int mn, mx;
int items = 0;

if(argc == 3) {
FILE* in=fopen(argv[1],"r+");
FILE* out=fopen(argv[2],"w");
if(in && out) {
setbuf(in, NULL);
setbuf(out, NULL);
while((items = (fscanf(in, "%s %d %d", &s, &mn, &mx))) > 0) {
switch(s[0]) {
case 'n':
/* print nos. to out */
while(mn++ < mx) {
fprintf(out, "%d\n", mn);
fflush(out);
}

break;
case 'e': fclose(in); fclose(out); return 0;
default:
/* error */
break;
}
}
fclose(in);
fclose(out);
}

} else {
fprintf(stderr, "Wrong no arguments\n");
}

return 0;
}

最佳答案

我所要做的就是删除打开输入文件时的+:

FILE* in=fopen(argv[1],"r");

我猜测,如果我将标准输入重定向到输入文件,那么标准输入只是一种方式 - 因此不允许输入文件可写。

关于c - 如何编写监视文本文件中新数据的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22122096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com