Shay
Shay

Reputation: 33

Reading strings from a text file in C and determining end of line

I am trying to read words and numbers from a space and tab delimited text file. I need to identify lines which contain "Step" and "False". I also need to store each word or number separately so that some can be thrown out later.

I am having trouble trying to write the part of the code which identifies "False" at the end of a line. I need the code to recognize that it has reached False and break the for loop.

Note: It is designed so that you input your own path. This portion works. Also, I have read that fscanf is much harder to use than fgets and fputs, but the data files i am reading are very consistent in format. This seems to work well for my purposes, as some entries will need to be doubles.

    int j;
    int k;
    char i[4];                       
    char File_path[40];
    char dummy;
    char stuff[7] = "False"

    printf("Input Path: ");
    scanf("%s", &File_path);
    printf("Reading:  %s\n\n",File_path);
    FILE *fp;
    fp=fopen(File_path, "r");
    for(j=0; j<7 && i != stuff; j++)
    {
        fscanf(fp,"%s",i);
        fprintf(stdout,"Read:  %s\n",i);
    }
    fclose(fp);

The file I am reading is:

True.0 kinda false False False

This returns:

Reading:  c:\\Data\\1.txt

Read:  True.0
Read:  kinda
Read:  false
Read:  False
Read:  False
Read:  False
Read:  False

I have tried changing stuff to "False" and I get the same result.

Upvotes: 3

Views: 1479

Answers (1)

Carl Norum
Carl Norum

Reputation: 225032

You can't compare strings that way in C. You need to use strcmp() or strncmp() to do that:

for (j = 0; j < 7 && strcmp(i, stuff); j++)

That loop conditional will break the first time i points to "False". You also need to make i larger - you're going to overflow that buffer on the first read in your example.

Editorial - you really do probably want to use fgets() and strtok() or one of its relatives to work through this stuff.

Upvotes: 4

Related Questions