逐字逐句地读取文件

时间:2013-05-06 14:27:57

标签: c file scanf

我有一个自定义档案,结构如下:

%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%包含档案中文件的名称
%dirs%包含目录的名称
%content%列出文件内容。

由于我需要打印指定文件的内容,我想逐字逐句阅读此档案,以识别%content%标签和文件名。
我知道fscanf()的存在,但只有当你知道存档模式时,它似乎才有效。

是否有C库或命令,如C ++的ifstream,允许我逐字阅读?

由于

2 个答案:

答案 0 :(得分:11)

您可以使用fscanf一次只读一个字:

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

如果您不知道每个单词的最大长度,可以使用与this answer类似的内容来获取完整的行,然后使用sscanf代替,使用与该单词一样大的缓冲区创建阅读完整的行。或者,您可以使用strtok将读取切片为单词。

答案 1 :(得分:1)

像这样

#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;
}
相关问题