0

I need to find when the string "#number of points NUM_PT" is seen in the given text file and then get+save the string that is on the next line in the txt file.

However, with this code I ultimately save the last string in the text file which is not what I want.

Program output image with more description: http://imgur.com/a/4ZhQ1

MY CODE:

#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;
}

THE INPUT TXT FILE:

#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
jjyj
  • 377
  • 4
  • 15
  • 1
    http://stackoverflow.com/questions/40538064/storing-numbers-as-x-y-cordinates-from-a-file-at-a-specific-point – BLUEPIXY Nov 14 '16 at 02:20
  • 1
    You keep on reading each line into `buf`, so you lose the value you think you have saved because it is overwritten by each subsequent line. You need to copy the saved value into another array. – Jonathan Leffler Nov 14 '16 at 02:20

0 Answers0