如何从文件中读取数字并将它们分配给它们实际意味着什么

时间:2015-02-15 00:35:30

标签: c arrays file-io

将C程序写入

  1. 计算安大略省一系列湖滩的大肠杆菌的平均水平
  2. 决定开放或关闭海滩
  3. 为数据文件中包含的所有湖泊和海滩生成报告。
  4. 对于每个海滩,文件中有一行数据,下面的字段用空格分隔 - 湖泊ID(整数),海滩编号(整数),采样数(整数)和一个实数(双)取样代表100毫升水中的生物数量。

    湖桌

    1: Ontario        
    2: Erie    
    3: Huron       
    4: Muskoka   
    5: Simcoe
    

    海滩桌

    100: Kew Beach       
    101: Sunnyside Beach  
    103: Sandbanks   
    201: Port Dover  
    202: Port Burwell  
    203: Crystal Beach   
    301: Goderich  
    302: Sauble Beach    
    303: Kincardine   
    401: Muskoka Beach   
    501: Sibbald Point   
    

    这是文件数据:

    1 100 12 47.7 52.2 45.5 78.7 45.5 33.2 50.4 60.2 48.9 43.3 49.9 50.6     
    1 101 9 75.5 53.2 65.1 81.1 44.1 42.2 41.1 39.7 51.1      
    2 201 3 56.6 49.7 45.5     
    2 202 2 44.4 66.6          
    5 501 4 55.5 34.4 66.6 22.2     
    4 401 4 33.3 44.4 55.5 66.6        
    3 301 3 50.0 51.1 49.8       
    3 302 4 77.7 66.6 22.2 33.3      
    3 303 3 55.5 55.5 44.0      
    1 103 1 13.3    
    

    我知道如何编写代码,但是我不知道的是如何使程序读取文件以及如何指定该特定数字是安大略湖,或者如何让程序对样本进行平均, 我第一次参加编程只有2个月,所以请耐心等待。

1 个答案:

答案 0 :(得分:0)

您可以在文件中编写块结构,以二进制文件保存数据。

用于创建结构

struct Lake_table {
    int id;
    char name[length];
};

struct Beach_table {
    int samplings;
    char name[length]
    double samplings_ml;

};

使用那样的数据初始化结构!

struct Lake_table lakes[] =  {
{1,"Ontario"}
{2,"Erie"}
{3,"Huron"}
{4,"Muskoka"}
{5,"Simcoe"}
};

struct Beach_table beaches[] = {
{100,"Kew Beach",0.0}
{101,"Sunnyside Beach",0.0}
{103,"Sandbanks",0.0}
{201,"Port Dover",0.0}
{202,"Port Burwell",0.0}
{203,"Crystal Beach",0.0}
{301,"Goderich",0.0}
{302,"Sauble Beach",0.0}
{303,"Kincardine",0.0}
{401,"Muskoka Beach",0.0}
{501,"Sibbald Point",0.0}
};

要保存结构,请执行此操作!

FILE *file;
const char file_name[] =  "filename.dat";
file = fopen(file_name,"wb");
if (file != EOF) {
    fwrite(beaches,sizeof(struct Beach_table),length,file);

}

让你的结构做到这一点!

struct Beach_table beaches;
FILE *file;
    const char file_name[] =  "filename.dat";
    file = fopen(file_name,"rb");
    if (file != EOF) {
        fread(beaches,sizeof(struct Beach_table),length,file);
    }

要访问数据,概念与数组,指针相同。祝你好运