c - 如何使用 fscanf 读取带有分隔符的文件?

标签 c file scanf delimiter

我正在尝试读取文件并将信息存储到以下缓冲区

    char bookCode[MAX];
    char title [MAX];
    char author [MAX];
    char year [MAX];
    float selfCost;
    float selfPrice;

我的文件数据如下所示

1738|Jane Eyre|Charlotte Bronte|1997|2.5|4.09
2743|The Kite Runner|Khaled Hosseini|2018|6.32|8.9
6472|Memoirs of a Geisha|Arthur Golden|2011|4.21|6.61
7263|The Divine Comedy|Dante|2009|5.59|7.98
3547|Outlander|Diana Gabaldon|1996|10.99|12.07

目前,我尝试了以下方法

while (fscanf(fi, "%[^|]|%[^|]|%[^|]|%[^|]|%f|%f",bookCode,title,author,year,&selfCost,&selfPrice)==6)

但它只读取一行,然后就停止了。有什么建议吗?

代码

#include <stdio.h>
#include <stdlib.h>
#define INPUT "HW2_file1.txt"
#define MAX 1000 

int main(void)
{

    FILE *fi = fopen(INPUT, "r");
    if (fi!=NULL)
    {
        printf ("Input file is opened sucesfully\n");
    }
    else
    {
        perror ("Error opening the file: \n");
        exit(1);
    }
    ReadingData(fi);

    fclose(fi);
    return 0;
}
void ReadingData (FILE *fi)
{
    int i=0;
    char bookCode[MAX];
    char title [MAX];
    char author [MAX];
    char year [MAX];
    float selfCost;
    float selfPrice;
    while (fscanf(fi, " %[^|]|%[^|]|%[^|]|%[^|]|%f|%f",bookCode,title,author,year,&selfCost,&selfPrice)==6)
    {

        printf ("%s %s %s %s %.2f %.2f\n",bookCode,title,author,year,selfCost,selfPrice);
        i++;
        printf ("%d\n",i);
    }
}

最佳答案

您的代码有效(只要我在调用之前重新排序定义ReadingData,添加必要的#include#define MAX,并简化它以摆脱未使用的 data 类型;我还压缩了变量声明以尝试使 TIO 链接适合注释,但这最终是徒劳的):

#include <stdio.h>

#define MAX 256

void ReadingData (FILE *fi)
{
    int i=0;
    char bookCode[MAX], title[MAX], author[MAX], year[MAX];
    float selfCost, selfPrice;
    while (fscanf(fi, " %[^|]|%[^|]|%[^|]|%[^|]|%f|%f",bookCode,title,author,year,&selfCost,&selfPrice)==6)
    {

        printf ("%s %s %s %s %.2f %.2f\n",bookCode,title,author,year,selfCost,selfPrice);
        i++;
        printf ("%d\n",i);
    }
}

int main(void)
{
    ReadingData(stdin);

    return 0;
}

Click this Try it online! link它会根据您提供的输入运行得很好。因此,要么您的输入是错误的,要么您省略了代码,要么您遇到了一些其他问题,而这些问题是由于缺乏最小的、可重现的示例而被隐藏的。

关于c - 如何使用 fscanf 读取带有分隔符的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58863878/

相关文章:

flutter - 如何将 API_KEY 放入 Flutter 应用程序中的 ".env"文件中?

c# - 在 C# 中写入 linux tty (/dev/) 文件

c - 通过scanf读取c中的两个数组时,第二个以某种方式修改了第一个

c - 如何让 fgets() 在开头忽略 a\n?

c - scanf 获取之前执行的 getchar() 的输入

c - 如果 getcwd() 和 getenv ("PWD") 不匹配,我该怎么办?

c - 导入地址表和全局偏移表有什么区别?

c - "dirCount"工作不正常

Python C 扩展 - 错误 `python3.6' : free(): invalid pointer: 0x

c++ - 在 C++ 中使用 Dos 命令时使用 GetLastError