繁体   English   中英

尝试读取和打印文件中的特定行

[英]Trying To Read And Print A Specific Line From an File

我正在尝试编写一个程序,以显示外部文件中的最小值,最大值和平均值。

这里的文件是:

31.6    22.4    25.9
30.2    22.7    25.5
31.2    22.9    26.1
31.3    23.4    26.4
30.7    23.2    26.2
31.3    23.1    26.4
31.6    23.9    26.4
31.6    24.0    26.9
32.7    24.7    27.5
33.8    24.8    27.7
32.4    25.0    27.6
32.1    24.9    27.6
32.7    25.4    27.9
31.9    25.5    27.6
31.9    25.4    27.8
32.1    25.3    27.8
31.7    25.6    27.8
32.6    25.2    27.7
32.2    24.9    27.5
32.2    24.9    27.7
31.7    25.8    27.7
32.3    25.5    27.9
32.1    24.4    27.3
31.5    24.6    27.2
31.8    24.0    27.0 
32.0    24.4    27.4 
32.4    24.9    27.8
32.1    25.0    27.6

这是主要代码:访问和读取文件:

#include <stdio.h>
#include <cstdlib>
void main(void)
{
    FILE *feb, *mar;
    int month, date, count = 0;
    double min, max, mean;
    char *pch;
    char line[256];

    printf("Input Month (2 or 3): ");
    scanf("%d", &month);

    if(month == 2)
    {
        feb = fopen("feb.txt", "r");

        if(!feb)
        {
            printf("404: File Not Found!");
        }

        else
        {
            printf("Input Date (1 ~ 28): ");
            scanf("%d", &date);
        }

        fclose(feb);
    }

    system("pause");
    return 0;
}

问题是; 我想不通一种方法,使其读取特定行并在输出屏幕上分别打印出值。

建议的方法,并带有示例:
1.创建一个结构。 例如:

typedef struct  {  
    double min;  
    double mean;  
    double max;  
} RECORD;  
RECORD *record;  

2.计算文件中的行数。 有很多方法可以执行此操作, 请参见此处的示例
给定您提供的示例数据(即,它似乎使用换行符 \\n ),这是另一个示例:

int longest=0;
int count = countLines("c:\\records.txt", &longest);

定义countlines位置:

int countLines(char *file, int *longest)
{
    char line[260]; 
    int len=0, lenKeep=0, count=0;
    FILE *fp = fopen(file, "r");
    if(fp)
    {
        while(fgets(line, 80, fp))
        {
            len = strlen(line);
            if(len > lenKeep) lenKeep = len;
            count++;
        }
        fclose(fp);
    }
    *longest = lenKeep;
    return count;
}

3.创建一个带有count元素的struct数组,以包含文件记录:

record = calloc(count, sizeof(RECORD));  
if(record)  
{... 

4.逐行读取文件(请参阅1.中的示例),然后使用sscanf或类似方法将行内容解析为struct数组的三个成员。 (使用sscanf的一些示例: hereherehere )。 给定您的行缓冲区是line ,并且i是0到count之间的某个值,这是使用sscanf一行解析示例:

sscanf(line, "%lf %lf %lf",&record[i].min, &record[i].mean, &record[i].max);  

5.通过使用所需的成员索引来打印选定的记录。 此代码遍历所有记录,例如:

for(i=0;i<count;count++)
{
    printf("%d: %f %f %f\n", i, record[i].min, record[i].mean, record[i].max);  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM