C - 将输入文件解析为行和字符

时间:2014-03-02 04:39:27

标签: c parsing input

我正在尝试编写一个C程序来解析输入文件,以便解析各个行,然后在每一行中,单个字符被进一步解析并存储在struct中的不同变量中。这是我到目前为止的代码(我设法解析单个字符而不考虑它们在哪一行):

/* create struct instances */
/* file open code */
...
int currentChar = fscanf(fp, "%s", storageArray);
while (currentChar != EOF) {
    printf("%s\n", storageArray);
    currentChar = fscanf(fp, "%s", storageArray);
}
...
/* file close code */

我如何调整我的代码,以便不会将每个单独的字符打印到屏幕上,而是获得如下行为:(注意:在我的程序中,我假设用户输入将有三个字符到一行。)

INPUT FILE:
a b c
f e d

LINE STRUCT 1:
char1 = a
char2 = b
char3 = c
LINE STRUCT 2:
char1 = f
char2 = e
char3 = d

我觉得解决方案可能涉及类似于我编写的while的嵌套循环,其中外部循环跟踪线条,内部循环跟踪字符。

3 个答案:

答案 0 :(得分:0)

试试这个

int i=1,j-1;    
printf("Line  STRUCT 1: ");
while( ( ch = fgetc(fp) ) != EOF ){
   if(ch=='\n'){
   printf("Line STRUCT %d \n",++i);
   j=1;
   }

  printf("Char %d  = %c \n",ch,j++);

}

答案 1 :(得分:0)

这样做:

for (int i=0; !feof(fp); i++)
    fscanf(fp,"%c %c %c ",
        &storageArray[i].char1,
        &storageArray[i].char2,
        &storageArray[i].char3);

答案 2 :(得分:0)

或试试这个:

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

#define READ_OPTIONS "r"

struct line {
    char char1;
    char char2;
    char char3;

    struct line* next;
};

struct line* g_lines = NULL;


int main(int argc, char** argv) {
    char buf[8] = {0};
    struct line* newline, *iter, *head;
    int counter = 1;

    FILE* fp = fopen("file.txt", READ_OPTIONS);

    if(NULL != fp) {
        while(fgets(buf, 8, fp)) {
            newline = malloc(sizeof(struct line));
            if(NULL != newline) {
                memset(newline, 0, sizeof(struct line));
                sscanf(buf, "%c %c %c",
                    &newline->char1,
                    &newline->char2,
                    &newline->char3);

                if(NULL != g_lines) {
                    for(iter = g_lines;
                        NULL != iter->next;
                        iter = iter->next);

                    iter->next = newline;

                } else g_lines = newline;   
            }
        }
        fclose(fp);
    } else return -1;


    /* print the contents */
    for(iter = g_lines;
        NULL != iter;
        iter = iter->next, 
        ++counter)
        printf("Line %d: char1=%c char2=%c char3=%c\n",
                counter, iter->char1, iter->char2, 
                iter->char3);


    /* 
        now to free memory before returning
        control to the operating system
    */
    for(iter = g_lines;
        NULL != iter;)
    {
        head = iter->next;
        free(iter);
        iter = head;
    }
    return 0;
}