我正在尝试通过fscanf读取文件test.txt并将其存储在struct数组中。这就是我尝试过的。这里的问题是fscanf
无法正常运行。读取文件后,我也尝试在屏幕上打印该文件,但是它不起作用。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Item {
double value;
int unit;
char name[50];
};
int load(struct Item* item, FILE* data);
void display(struct Item item, int variableA);
int main()
{
struct Item I;
int i;
char ck;
ck = fopen("test.txt", "r");
if (ck)
{
for (i = 0; i < 3; i++)
{
load(&I, ck);
display(I, 0); //DISPLAY FUNCTION THAT READS test.txt and DISPLAYS
}
fclose(ck);
}
return 0;
}
int load(struct Item* item, FILE* data)
{
fscanf(data, "%d,%.2lf,%s\n", &(*item).unit,&(*item).value,&(*item).name);
return 0;
}
void display(struct Item item, int variableA)
{
printf("|%3d |%12.2lf| %20s |***\n", item.unit, item.value, item.name);
return;
}
这是我在test.txt文件中所拥有的:
205,11.20,John Snow
336,23.40,Winter is coming
220,34.20,You know nothing
错误:程序在编译时带有一些警告,但是执行代码时出现分段错误。
知道为什么吗?
输出预期:应从test.txt文件读取OUTPUT,并应将其显示在屏幕上。
最佳答案
程序中的多个问题:
1。
char ck;
ck = fopen("test.txt", "r");
fopen
返回FILE*
,而不是char
,使用FILE* ck = fopen(...);
2。
fscanf(data, "%d,%.2lf,%s\n", &(*item).unit,&(*item).value,&(*item).name);
始终检查
fscanf
的返回值,如果它小于您请求的字段数,则以下对fscanf
的调用不太可能达到您的期望。另外,*item.unit
与item->unit
相同,请使用item->unit
,因为它更短且更干净:int ret = fscanf(data, "%d,%lf,", &item->unit, &item->value);
if (ret != 3) { // error }
第三,
%s
与一系列非空格字符匹配,因此,当fscanf
读取“ John”时,它将停止,并且下一个fscanf
调用将在读取“ Snow”的同时期望一个整数。因此,要输入带空格的字符串,请改用
fgets
,并记住最后要删除换行符。请尝试以下操作:
int main(void)
{
struct Item I;
int i;
FILE* ck;
int ret;
ck = fopen("test.txt", "r");
if (ck)
{
for (i = 0; i < 3; i++)
{
ret = load(&I, ck);
if (ret < 0)
break;
display(I, 0); //DISPLAY FUNCTION THAT READS test.txt and DISPLAYS
}
fclose(ck);
}
return 0;
}
int load(struct Item* item, FILE* data)
{
int ret = fscanf(data, "%d,%lf,", &item->unit, &item->value);
if (ret != 2) {
return -1;
}
fgets(item->name, sizeof item->name, data);
item->name[strlen(item->name)-1] = '\0';
return 0;
}
void display(struct Item item, int variableA)
{
printf("|%3d |%12.2lf| %20s |***\n", item.unit, item.value, item.name);
return;
}
它输出:
$ ./a.out
|205 | 11.20| John Snow |***
|336 | 23.40| Winter is coming |***
|220 | 34.20| You know nothing |***
关于c - C编程:读取文件并存储在struct数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40835625/