C读取,比较和保存txt文件内容

时间:2016-11-14 02:14:11

标签: c file readfile fgets strstr

我需要在给定的文本文件中找到字符串“#number of points NUM_PT”,然后获取+保存txt文件中下一行的字符串。

但是,使用此代码,我最终将最后一个字符串保存在文本文件中,这不是我想要的。

对节目输出图像进行更多说明:http://imgur.com/a/4ZhQ1

我的代码:

#include<stdio.h>
#include<string.h>
#include<stdbool.h>
#pragma warning (disable : 4996) //Used to remove microsoft Deprecated.

int main(void)
{
    /*VARIABLES AND DEFINE: START*/ /*VARIABLES AND DEFINE: START*/

    //FILE VARIABLES:
    FILE *file;
    char buf[1000];
    file = fopen("Sample.txt", "r");

    //CONDITION VARIABLES:
    bool searchNUM_PT = false;

    //FILE EXTRACT VARIABLES:
    char *NUM_PT = "EMPTY";

    //DEBUG AND VISUAL AID:
    int line_count = 0;

    /*VARIABLES AND DEFINE: START*/ /*VARIABLES AND DEFINE: START*/


    if (file == NULL) {
        perror("Error\n");
    }

    else {
        printf("File read success.\nContent withing file below:\n\n");

        while (fgets(buf, sizeof(buf), file) != NULL) {
            printf("%4d|    %s", line_count, buf);

            if (searchNUM_PT == true) { 
                NUM_PT = buf; //Gets the string that is in buf and stores it in NUM_PT, I feel like my understanding of this part may be wrong? 
            }

            if (strstr(buf, "#number of points NUM_PT")) { //Used to compare buf w/ the string I am looking for.
                printf("A match was found on line #: %d\n", line_count);
                searchNUM_PT = true; //Found the string....in the next iteration of this loop it will get the string after "#number of points NUM_PT"
            }
            line_count += 1; //Used to display line number
        }


        printf("\n\nEnd of content......\n\n");

    }

    printf("\nNUM_PT is: %s\n", NUM_PT);
    fclose(file);

    return 0;
}

INPUT TXT文件:

#instance10_001.txt
#area [0, MAX_X] x [0, MAX_Y]
100 100
#number of points NUM_PT
10
#coordinates
0   0
0   90
70  100
100 50
30  30
30  70
70  70
70  30
50  50
45  0
#end of instance

0 个答案:

没有答案