C fscanf 从文件错误中读取数据

标签 c crash scanf

我是 C 的新手,我正在尝试编写一个程序,该程序将从文件中读取数据并将它们存储在数组中(以便我以后可以使用它们)。

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


int day[3], month[3], year[3], hour[3], minute[3], second[3];
float value[3];


int main()
{  
    // Open the file for read
    FILE* file1 = fopen("test.txt", "r");

    // Safety check
    if (file1 == NULL)
    {
        printf("Error: file1 == NULL\n");
        getchar();
        return 0;
    }

    // Open the new file for write
    FILE* file2 = fopen("new.txt", "w");

    // Safety check
    if (file2 == NULL)
    {
        printf("Error: file2 == NULL\n");
        getchar();
        return 0;
    }


    int j = 0;

        for (j = 0; j < 4; j++)
        {
            int count = fscanf(file1, "%d-%d-%d %d:%d:%d %f", &day[j], &month[j], &year[j], &hour[j], &minute[j], &second[j], &value[j]);
            printf("%d-%d-%d %d:%d:%d %f\n", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
            // Check for finising early
            if (count == EOF)
            {
                printf("EOF");
            }
        }

    // Close the original file
    fclose(file1);
    // Close the target file
    fclose(file2);  

    getchar();
}

该文件包含以下格式的数据:

20-03-17 08:49:01 28,515
20-03-17 08:49:31 29,1837
20-03-17 08:50:01 27,845

评论后编辑:

代码现在不会再崩溃,而且几乎可以完美运行!

结果是这样的:

20-3-17 8:49:1 28.514999
20-3-17 8:49:31 29.183701
20-3-17 8:50:1 27.844999
1105469112-1-20 17:8:49 0.000000

有没有办法解决小数问题? 知道最后一行是什么吗?

感谢您的宝贵时间!

最佳答案

在这里:

for (j = 0; j < 3; j++)
{
    int count = fscanf(file1, "%i-%i-%i %i:%i:%i %f ", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
    printf("%d-%d-%d %d:%d:%d %f\n", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
    // Check for finising early
    if (count == EOF)
    {
        printf("EOF");
    }
}

&放在你想读取的每个变量之前。

喜欢:

for (j = 0; j < 3; j++)
{
    int count = fscanf(file1, "%i-%i-%i %i:%i:%i %f ", &day[j], &month[j], &year[j], &hour[j], &minute[j], &second[j], &value[j]);
    printf("%d-%d-%d %d:%d:%d %f\n", day[j], month[j], year[j], hour[j], minute[j], second[j], value[j]);
    // Check for finising early
    if (count == EOF)
    {
        printf("EOF");
    }
}

问题编辑后:

好的,问题是您的数据文件 (test.txt) 的格式如下

20-03-17 08:49:01 28,515

,不是

20-03-17 08:49:01 28.515

因此 %f 将只读取 28,而不是 28.515(因为 , 不用于 float 数)。您有两个选择:(1) 将数据文件中的 28,515 更改为 28.515 (2) 读取 28515 分别。我认为第一个选择会很好。

关于C fscanf 从文件错误中读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43169224/

相关文章:

c - 生成非唯一(重复)排列

MySQL 在 SQL 上崩溃

iOS App 在没有任何崩溃日志的情况下退出

c - fscanf 更改字符串变量?

C fifo 保持阻塞

c - :protocol pseudo-header in http2? 在静态表中的索引号是多少

c - 不是一切都在它应该在的地方,为什么会出现段错误?

c - scanf 十六进制到 C 中的 uint8_t

C 将两个小字符串连接成一个大字符串

ios - 如何在没有xcode的情况下在iPhone本身上进行调试? UISearchBar/DisplayController 崩溃