Reading from a file word by word [closed]

2019-02-20 13:39发布

问题:

I have a custom archive structured as follows:

%list% name1 name2 name3 %list%

%dirs% archive directories %dirs%

%content% name1 path1 content of file1 %content%
%content% name2 path2 content of file2 %content%
%content% name3 path3 content of file3 %content%

%list% contains names of files in archive
%dirs% contains names of directories
%content% lists file contents.

Since i need to print the content of a specified file, i want to read this archive word by word, in order to identify %content%tag and file name.
I know the existence of fscanf(), but it seems to work efficiently only if you know the archive pattern.

Is there a C library or command, like ifstream for C++, that allows me to read word by word?

Thanks

回答1:

You can just use fscanf to read one word at a time:

void read_words (FILE *f) {
    char x[1024];
    /* assumes no word exceeds length of 1023 */
    while (fscanf(f, " %1023s", x) == 1) {
        puts(x);
    }
}

If you don't know the maximum length of each word, you can use something similar to this answer to get the complete line, then use sscanf instead, using a buffer as large as the one created to read in the complete line. Or, you could use strtok to slice the read in line up into words.



回答2:

like this

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

typedef char Type;

typedef struct vector {
    size_t size;
    size_t capacity;
    Type *array;
} Vector;

Vector *vec_make(){
    Vector *v;
    v = (Vector*)malloc(sizeof(Vector));
    if(v){
        v->size = 0;
        v->capacity=16;
        v->array=(Type*)realloc(NULL, sizeof(Type)*(v->capacity += 16));
    }
    return v;
}

void vec_add(Vector *v, Type value){
    v->array[v->size] = value;
    if(++v->size == v->capacity){
        v->array=(Type*)realloc(v->array, sizeof(Type)*(v->capacity += 16));
        if(!v->array){
            perror("memory not enough");
            exit(-1);
        }
    }
}

void vec_reset(Vector *v){
    v->size = 0;
}

size_t vec_size(Vector *v){
    return v->size;
}

Type *vec_getArray(Vector *v){
    return v->array;
}

void vec_free(Vector *v){
    free(v->array);
    free(v);
}

char *fin(FILE *fp){
    static Vector *v = NULL;
    int ch;

    if(v == NULL) v = vec_make();
    vec_reset(v);
    while(EOF!=(ch=fgetc(fp))){
        if(isspace(ch)) continue;//skip space character
        while(!isspace(ch)){
            vec_add(v, ch);
            if(EOF == (ch = fgetc(fp)))break;
        }
        vec_add(v, '\0');
        break;
    }
    if(vec_size(v) != 0) return vec_getArray(v);
    vec_free(v);
    v = NULL;
    return NULL;
}

int main(void){
    FILE *fp = stdin;
    char *wordp;
    while(NULL!=(wordp=fin(fp))){
        printf("%s\n", wordp);
    }
    return 0;
}


标签: c file scanf