gpt4 book ai didi

c - 将文件中的值存储到数组

转载 作者:行者123 更新时间:2023-11-30 16:56:48 26 4
gpt4 key购买 nike

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。任何帮助都会很热心。

最佳答案

一般来说,避免使用 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");
}
}
}

关于c - 将文件中的值存储到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39809324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com