【问题标题】:How to print a struct using a file in C如何使用 C 中的文件打印结构
【发布时间】:2023-03-19 11:47:01
【问题描述】:

数据文件包含迈阿密和多伦多的天气数据(城市名称、日期、温度、降水量)。我需要创建一个打印结构但值在 .txt 文件中的函数。这是文件:(info.txt)

Miami,2,-6.4,0
Toronto,2,9.5,0.8
Miami,3,-11.7,0
Toronto,3,6.1,0

这是结构:

struct Weather{

    char location;  //will be "M" or "T"
    int daynum;
    double temp;
    double precip;
};

这是一个解析器函数:

void parseLine(char toParse[], struct Weather * toLoad)
{     
    char * theToken;     
    theToken = strtok(toParse, ",");     
    toLoad->location = theToken[0];     
    theToken = strtok(NULL, ",");     
    toLoad->daynum = atoi(theToken);     
    theToken = strtok(NULL, ",");     
    if(theToken != NULL)
    {         
        toLoad->temp = atof(theToken);     
    }     
    else     
    {         
        toLoad->temp = -400;     
    }     
    theToken = strtok(NULL, ",");     
    if(theToken != NULL)     
    {         
        toLoad->precip = atof(theToken);     
    }     
    else     
    {         
        toLoad->precip = -1.0; 
    }
}

所以我的问题是如何使用 struct 和 parse 函数创建另一个函数来打印 location、daynum、temp 和 precip 的值。

注意:我在我的主函数中使用了 argc 和 argv。您还应该知道我是文件操作的新手,所以我不确定如何正确使用文件函数。

编辑:我的主要问题是弄清楚在“主”中做什么,以便我可以创建打印功能

【问题讨论】:

  • 我不太明白这个问题。为什么不能只使用 printf?看起来你已经完成了“更难”的部分。
  • 使用类似 printf("%s,%d,%lf,%lf", st->location == 'M' ? "Miami" : "Toronto", st 有什么问题->daynum, st->temp, st->precip); ?
  • 但我不必打开文件并处理文件,这是主要问题(在“主要”中我不确定该怎么做)
  • @JohnSmith 您是否打算修改输入文件?你想读取文件,修改它的数据,然后把它写回来吗?在这种情况下,您可能希望让您的parseLine 函数采用FILE *,并将其传递给stdin。这样你就可以像这样运行程序:myProg.exe < info.txt > info.txt.
  • 不,我不想修改它的数据。如果您的回答有效,我会尽快回复您

标签: c struct file-manipulation


【解决方案1】:

你想要这样的东西吗?

void printStruct(FILE *fout, struct Weather *in)
{
    fprintf(fout, "%s,%d,%f,%f", in->location == 'M' ? "Miami" : "Toronto", in->daynum, in->temp, in->precip);
}

如下使用:

#include <stdio.h>

#define ELEMSIZE(arr) (sizeof(*arr))
#define ARRAYSIZE(arr) (sizeof(arr)/ELEMSIZE(arr))

int main(void)
{
    char line[1024];
    struct Weather weather;
    FILE *fp;

    fp = fopen("info.txt", "r");
    fread(line, ELEMSIZE(line), ARRAYSIZE(line), fp);
    parseLine(line, &weather);
    printStruct(stdout, &weather);
    fclose(fp);

    return 0;
}

注意:您可能希望将parseLine 的第一个参数更改为FILE *(您必须做一些魔术才能让strtok 工作,但它会提高效率以及灵活性和可伸缩性)。

【讨论】:

  • 所以当我尝试运行它时会收到大量错误/警告
  • 啊你没有使用 argc/argv
  • @JohnSmith 它应该编译,但我没有检查...更新:我收到的所有警告都来自从您的问题复制的编码。
猜你喜欢
  • 2017-02-17
  • 2017-06-24
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多