简体   繁体   中英

How to stop reading a file when you reach a period in C

I need to read a file where it will a single dot string denotes the end of a text. I think I am only allowed to use either strcmp or sscanf. Here is an example:

This is a sample text.

The file will be terminated by a single dot: .

The program continues processing the lines because the dot ( . ) did not appear at the beginning.

. even though this line starts with a dot, it is not a single dot. The program stops processing lines right here.

.

You won't be able to feed any more lines to the program.


#include <stdio.h>
#include <stdlib.h> // For exit() function
#include <string.h>


int main() {
    char str[255];
    FILE *fp;

    if ((fp = fopen("file.txt.rtf", "r")) == NULL) {
        printf("Error! opening file");
        return 1;
    }
    
    while(!feof (fp))
    {
        
        fgets(str, 255, fp);
        printf("%s",str);
        if (strcmp(str, ".")==0)
        {
            break;
        }


    }
    fclose(fp);
    return 0;
}

I'm suspicious about this:

current->next!=NULL && strcmp(str, current->data)>0

That navigates until there's a match, at which point the node is replaced. You might kick out an entry and replace it, breaking the chain.

If this is to prevent duplicates then it'd make sense to allocate if and only if you need to insert, and do that only after you've hit the NULL chain terminator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM