c - 从文件中逐行读取并保存在列表中 C

标签 c list file

我的问题是从一个 100 行的文件中读取,每行有 4 个字段(由 4 个空格分隔),如下所示:

0007 0007 NOVO BANCO, SA 银行

0008 0008 BANCO BAI EUROPA, SA Bancos

0010 0010 BANCO BPI, SA 银行

等...

完成此操作后,我必须将其保存在链表中。

我有这个:

struct list{
    int code1;
    int code2;
    char name[100];
    char type[100];
    struct list *next, *current;    
};

int main()
{

    FILE *fp1;
    struct list iban;

    fp1 = fopen("ibanlist.txt", "r");
    if(fopen == NULL)
    {
         printf("Error!");
    }

    fscanf(fp1, /*what should i do here?*/, iban.code1, iban.code2, iban.name, iban.type);
    //should i use fgets and sscanf instead?

    fclose(fp1);
    return 0;
}

我的问题是如何从带有空格的文件中读取。例如,在第三个字段中,它在“,”之后有一个空格。这也是我第一次使用列表,谁能告诉我如何做?

最佳答案

这使用 strstr 来标记输入字符串。数据中的第一个分隔符只有 3 个空格,其余为 4 个,因此在每种情况下我都查找 3,然后前进到所有连续的空格。

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

struct list{
    int code1;
    int code2;
    char name[100];
    char type[100];
};

int main(void)
{
    FILE *fp;
    char str [1000];
    char *aptr, *bptr, *cptr;
    struct list rec;

    if ((fp = fopen("file.txt", "rt")) == NULL)
        return 1;

    while(fgets(str, sizeof str, fp) != NULL) {
        // break the input line
        aptr = strstr(str, "   ");              // isolate first field
        if(aptr == NULL)
            return 1;
        *aptr++ = '\0';
        while (*aptr == ' ')
            aptr++;

        bptr = strstr(aptr, "   ");             // isolate second field
        if(bptr == NULL)
            return 1;
        *bptr++ = '\0';
        while (*bptr == ' ')
            bptr++;

        cptr = strstr(bptr, "   ");             // isolate third field
        if(cptr == NULL)
            return 1;
        *cptr++ = '\0';
        while (*cptr == ' ')
            cptr++;

        cptr [ strcspn(cptr, "\r\n") ] = 0;    // remove trailing newline etc

        // extract the data
        if(sscanf(str, "%d", &rec.code1) != 1)
            return 1;
        if(sscanf(aptr, "%d", &rec.code2) != 1)
            return 1;
        strcpy(rec.name, bptr);
        strcpy(rec.type, cptr);

        // print the result
        printf("%d/%d/%s/%s\n", rec.code1, rec.code2, rec.name, rec.type);
    }
    fclose(fp);
    return 0;
}

程序输出:

7/7/NOVO BANCO, SA/Bancos
8/8/BANCO BAI EUROPA, SA/Bancos
10/10/BANCO BPI, SA/Bancos

关于c - 从文件中逐行读取并保存在列表中 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35866751/

相关文章:

python - 生成器到列表转换的不同速度

file - 如何使用javafx从目录中获取所有文件

c - 为什么使用 gprof 会阻止程序的执行?

在 C 中将单个整数与整数数组进行比较?

c - 向二进制添加奇偶校验,即汉明码

c - 将文件中的数据添加到数组

java - 防止文件碎片

c - Bit Twiddling - 对该程序的输出感到困惑

r - R 中的 lapply 函数可以返回命名列表吗?

r - 根据组包含的值计算组之间观察计数的差异