Read WORDS (not char) from file without empty line

2019-09-21 21:31发布

This question is an exact duplicate of:

Hi. I need to read several files without empty lines between words.They can have different layouts, such as 1.txt or 2.txt:


1.txt:

treg
hreger
ig
srg
fre
ig
lre
eg

2.txt:

lregreg

igregr

kreggerg

ereherh

tershs

hsehsteh

asreh

treshse

How do i do that ? How can I count the number of words in the fastest way? I just have the following code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(){
    FILE *fp;
    char palavra[50]="/0";
    char *s;

    fp = fopen("1.txt","r");
    if(fp == NULL){
    puts("Open file failed\n");
    exit(-1);
    }

    while(fscanf(fp,"%s",palavra)!=EOF){
    s=palavra;
        /*do things with s var*/
    }

    fclose(fp);
    exit(0);
}

how i implement something like that:

while ((c = fgetc(fp)) != EOF) { 
    if (isspace(c)){ 
        continue;
    }

标签: c file lines words
1条回答
何必那么认真
2楼-- · 2019-09-21 22:19
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

enum status { OUT, IN };

int main(){
    FILE *fp;
    int ch, wc = 0, stat = OUT;

    if(NULL==(fp = fopen("1.txt","r"))){
        fprintf(stderr, "Open file failed\n");
        exit(-1);
    }

    while(EOF!=(ch=fgetc(fp))){
        if(isspace(ch)){
            stat = OUT;
        } else {
            if(stat == OUT){
                stat = IN;
                ++wc;
            }
        }
    }
    fclose(fp);
    printf("number of words is %d.\n", wc);

    return 0;
}
查看更多
登录 后发表回答