简体   繁体   English

Fscanf还是Fgets? 一行一行地读取文件

[英]Fscanf or Fgets? Reading a file line after line

i have to write a program in C to read a file containing several line of text, each line contains two variables: a number (%f) and a string: 我必须在C中编写一个程序来读取包含几行文本的文件,每行包含两个变量:一个数字(%f)和一个字符串:

EX: file.txt
============
24.0 Torino
26.0 Milano
27.2 Milano
26.0 Torino
28.0 Torino
29.4 Milano

There is my code: 有我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
    int r, line = 0, found = 0;
    float temp, t_tot = 0;
    char loc[32];


    FILE *fp;

    fp = fopen(argv[1], "r");

    if (fp == NULL)
    {
        printf ("Error opening the file\n\n'");
        exit(EXIT_FAILURE);
    }

    if (argc == 3)
    {
        r = fscanf(fp, "%f %s\n", &temp, loc);

        while (r != EOF)
        {
            line++;

            if (r == 2)
            {
                if(strcmp(argv[2], loc) == 0)
                {
                    t_tot += temp;
                    found++;
                }
            }
            else
                printf ("Error, line %d in wrong format!\n\n", line);
        }

        printf ("The average temperature in %s is: %.1f\n\n", argv[2], (t_tot/found);
    }

}

The program needs to read all the line and find the city i wrote on argv[2] . 该程序需要读取所有行,并找到我在argv[2]上写的城市。 Than it will tell me the average temperature on that city, notifying me if a line in the file is in a wrong format. 比它会告诉我那个城市的平均温度,通知我文件中的一行是否格式错误。

The program is compiling correctly to me but it not output anything on screen... how can i solve that? 程序正在编译给我,但它没有在屏幕上输出任何东西......我怎么能解决这个问题? Is it correct to use fscanf on this case or it's better fgets ? 在这种情况下使用fscanf是正确的还是更好的fgets

I'm a student so, please, give me an "academical" way to resolve it :) 我是学生,所以,请给我一个“学术”的方法来解决它:)

A couple of things. 有几件事。

First, you gotta use fclose(). 首先,你必须使用fclose()。
Second, your code needs to fscan() each line in the file. 其次,您的代码需要fscan()文件中的每一行。 Not just before the while() loop, but within each while loop you gotta fscan() for the next iteration. 不仅在while()循环之前,而且在每个while循环中你都需要fscan()进行下一次迭代。
Third, you weren't figuring the average temperature, you're figuring the sum of all the tempuratures found. 第三,你没有计算平均温度,你正在计算所有发现的tempuratures的总和。 Fix that by changing "t_tot" to "(t_tot / found)" in your last printf(). 通过在最后一个printf()中将“t_tot”更改为“(t_tot / found)”来解决此问题。

Lastly, I'm not sure why you're not getting any output. 最后,我不确定为什么你没有得到任何输出。 Your input is like "myprogram file.txt Milano" right? 你的输入就像“myprogram file.txt Milano”对吗? Works for me. 适合我。 Anyway, here's your (edited) code back: 无论如何,这是你的(编辑过的)代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
    int r, line = 0, found = 0;
    float temp, t_tot = 0;
    char loc[32];

    FILE *fp;
    fp = fopen(argv[1], "r");

    if (fp == NULL)
    {
        printf ("Error opening the file\n\n'");
        exit(EXIT_FAILURE);
    } else {

        if (argc == 3)
        {
            r = fscanf(fp, "%f %s\n", &temp, loc);
            while (r != EOF)
            {
                line++;
                if (r == 2)
                {
                    if(strcmp(argv[2], loc) == 0)
                    {
                        t_tot += temp;
                        found++;
                    }
                }
                else
                    printf ("Error, line %d in wrong format!\n\n", line);
                r = fscanf(fp, "%f %s\n", &temp, loc);
            }
            printf ("The average temperature in %s is: %.1f\n\n", argv[2], (t_tot / found));
        }

    fclose(fp);

    }
}

you must put fscanf line inside the while loop 你必须在while循环中放入fscanf行

    while (1)
    {
        r = fscanf(fp, "%f %s\n", &temp, loc);
        if( r == EOF ) 
           break;
        .........................
    }

finally close the file 最后关闭文件

if u are using fgets change as follows 如果您使用fgets更改如下

  char s[256];
  while( fgets( s, 256, fp) != NULL )
  {
     sscanf( s, "%f %s", &temp, loc);
     .............
  }

Your code does not call fscanf in the loop like it should: the read is done once, and then the program either exists right away if the file is empty, or loops indefinitely. 你的代码不会像它应该的那样在循环中调用fscanf :读取完成一次,然后如果文件为空则程序立即存在,或者无限循环。

You should move the call of fscanf inside the while loop. 你应该在while循环中移动fscanf的调用。 One typical way of coding it is placing the assignment inside the loop header, like this: 编码它的一种典型方法是将赋值放在循环头中,如下所示:

while ((r = fscanf(fp, "%f %s\n", &temp, loc)) != EOF) {
    ...
}

modify the code like this... just put another fscanf in while statement. 像这样修改代码......只需在while语句中添加另一个fscanf。

if (argc == 3)
{
 r = fscanf(fp, "%f %s\n", &temp, loc);
  while(r != EOF )

    {
        r = fscanf(fp, "%f %s\n", &temp, loc);  
        line++;

        if (r == 2)
        {
            if(strcmp(argv[2], loc) == 0)
            {
                t_tot += temp;
                found++;
            }
        }
        else
            printf ("Error, line %d in wrong format!\n\n", line);
    }

    printf ("The average temperature in %s is: %.1f\n\n", argv[2], t_tot);
}

}

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

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