如何阅读不断更新的文本文件(如.log)?这称为流吗?

时间:2019-04-03 21:22:14

标签: c stream

我正在用C编写一个程序,该程序将读取日志文件并不断寻找特定的字符串。它显然还不完整。现在,我有了它,它将在.log中获取所有行的数量,从.txt文件中的某个行号开始,然后转到EOF或直到找到某个字符串。再往前走,如果我这样做,我将不得不不断地更新文本文件中的行号作为起点。

有人告诉我,有一种方法可以让我的程序在查找某个字符串时读取.log的“流”,然后我可以使它执行我想要的操作。我该怎么做?我不是很先进,所以非常感谢您对方法的评论和解释。如果编码有点混乱,请原谅我的编码。一旦我能够以最终形式获得想要的东西,肯定会对其进行修复。

我需要比显然与之前提出的另一个问题更好的理解和解释。


    #define MAX_LENGTH 500
    #define _CRT_SECURE_NO_WARNINGS
    #include <stdio.h>
    #include <stdlib.h> //for exit();
    #include <string.h>


    int main() {
        char errorCheck[MAX_LENGTH] = {"ERROR: Problem Accessing System Db! - bIsRunning, 1"}; //this will be the string the program searches for.
        char ec_processLog[MAX_LENGTH];
        char oldLineNumberFile[MAX_LENGTH]; //might change
        long int newLineNumberFile[MAX_LENGTH]; //might change
        long int oldLineNumber, newLineNumber;
        char line[MAX_LENGTH];
        int resultOfCompare, lineCount = 1, found = 0;

        FILE *fp1; //used to open ec_process.log
        FILE *fp2; //used as our line starting point
        FILE *fp3; //will be our error log file
        fp1 = fopen("C:/Script testing/ec_process.log", "r");
        fp2 = fopen("C:/Script testing/Fix/lineNumber.txt", "r");
        fp3 = fopen("C:/Script testing/Fix/returnityFixErrors.txt", "w");

        if (fp1 == NULL || fp2 == NULL) {
            fprintf(fp3, "ERROR with ec_process.log file and/or lineNumber file");
            exit(1);
        }


        while (fgets(oldLineNumberFile, sizeof oldLineNumberFile, fp2)) {

            oldLineNumber = atoi(oldLineNumberFile);  //atoi() converts string to integer
        }

        while (fgets(line, sizeof line, fp1) != NULL) { //This lets me go line by line in a file, reading each line one-by-one
            //In doing so, i can use a IF loop to where once my line++ goes to a certain number, that's where i will start my
            //FOR loop
            line[strcspn(line, "\n")] = '\0';  // Lop off potential \n


            if (lineCount >= oldLineNumber) {

                resultOfCompare = strcmp(errorCheck, line);

                if (resultOfCompare == 0) {
                    printf("FOUND %s\n ON LINE: %ld", line, lineCount);
                    found++;
                    break;
                }
                else {
                    lineCount++;
                    continue;
                }

            }else {
                lineCount++;
            }

        }


        getchar();
        getchar();

        return 0;

    }

0 个答案:

没有答案