将值从文件存储到数组

时间:2016-10-01 17:06:13

标签: c

int main() {
    char input[50];
    setbuf(stdout,0);
    printf("Please enter filename");
    scanf("%s",input);
    cfPtr = fopen(input, "r");

    int i;

    if (cfPtr == NULL)
    {
        printf("Error Reading File\n");
        exit (0);
    }

    for (i = 0; i < 1440; i++)
    {
        fscanf(cfPtr, "%d", &okay[i] );
        fclose(cfPtr);
    }
}

我似乎无法使用此功能,该文件属于(csv)类型并具有以下内容:

Time    On/off
00:00   0
00:01   0
00:02   0
00:03   0
00:04   0
00:05   0
00:06   0
00:07   0
00:08   0
00:09   0
00:10   0
00:11   0
00:12   0
00:13   0
00:14   0
00:15   0
00:16   0
00:17   0
00:18   0
00:19   0

持续24小时。我想要的只是将这些值存储到一个数组中。该文件名为HeatingSchedule00.csv。任何帮助都会很热。

1 个答案:

答案 0 :(得分:0)

一般情况下,请避免scanffscanf。他们遇到的麻烦是如果他们没有完全读取一行,你可能会把文件句柄卡在一条线的中间。这就是你发生的事情。 fscanf无法解析第一行,因为它不包含数字,而且只是一遍又一遍地执行此操作。

从文件中读取和解析行的一般安全方法是首先使用fgets读取整行,然后使用sscanf进行扫描。

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

int main() {
    char input[256];
    setbuf(stdout,0);
    printf("Please enter filename: ");

    /* ALWAYS put a limit on %s in scanf, else you risk a buffer overflow if
       there's more input than you allocated memory for. */
    scanf("%255s",input);

    FILE *cfPtr = fopen(input, "r");
    if( cfPtr == NULL ) {
        fprintf(stderr, "Couldn't open %s: %s\n", input, strerror(errno));
        exit(1);
    }

    char line[1024];
    char header1[21];
    char header2[21];
    while( fgets(line, 1024, cfPtr) ) {
        int hour, min, setting;

        /* Scan for the numbers first because they're more common */
        if( sscanf(line, "%d:%d\t%d", &hour, &min, &setting) == 3 ) {
            printf("%02d:%02d is %d\n", hour, min, setting);
        }
        else if( sscanf(line, "%20s\t%20s", header1, header2) == 2 ) {
            printf("Header: %s, %s\n", header1, header2);
        }
        else {
            fprintf(stderr, "unknown line");
        }
    }
}