读/写文本字符串

时间:2015-02-14 16:00:04

标签: c string file

我正在尝试学习如何在C语言中操作txt文件。该程序应在population.txt(http://pastebin.com/Q5fNRuJG)中读取,找到最高人口并显示它,制作人口超过100万的文件,制作一个包含所有爱尔兰城市的文件,并打印总人口。它只创建空文件,并打印总人口(现在还打印人口最多的城市)。有人可以帮忙吗?

该计划(在Borland编制):

//Program that filters and processes data with fscanf()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

main()
{
    FILE *fp;
    FILE *ireland;
    FILE *mmplus;
    int pop;
    int highest_pop=0;
    char country[50];
    char city[50];
    int total_pop=0;

    fp = fopen("population.txt","r");
    ireland = fopen("ireland_pop.txt","w");
    mmplus = fopen("greater_than_1MM.txt","w");

    //Checking if the file opened correctly
    if (fp==NULL)
    {
        printf("Cannot open file.\n");
        exit(1);
    }//End if

    //Scanning fp row by row
    while (fscanf(fp, "%s" "%s" "%i", country, city , &pop) != EOF)
    {
        //Getting the total population
        total_pop=total_pop+pop;

        //Storing the highest pop
        if (pop > highest_pop)
        {
            highest_pop=pop;
        }//End if

        //Finding 1 million+ cities
        if(pop>=1000000)
        {
            fprintf(mmplus,"%s %s %d\n",country,city,pop);
        }//End if

        //If the city is in Ireland
        if (strcmp("ireland",country) == 0)
        {
            fprintf(ireland,"%s %s %d\n",country,city,pop);
        }//End if
    }//End while

    rewind(fp); //Fix 1

    while (fscanf(fp, "%s" "%s" "%d", country, city , &pop) != EOF)
    {
        //Finding the city with the highest population
        if (pop == highest_pop)
        {
            printf("The city with the highest population is %s, %s, with a population of %d",city, country, pop);
        }//End if
    }//end while

    printf("The total population of all the cities is %d.",total_pop);
    getchar();
    fclose(fp);
    fclose(ireland);
    fclose(mmplus);
}

2 个答案:

答案 0 :(得分:0)

我第一次运行你的程序时,我得到了空文件。我第二次运行它得到了正确的输出。我第三次收到一个正确的文件和一个不正确的文件。

我可能输入了ctrl-C来结束程序。所以我对程序的最后几行做了一些更改 - 将newline添加到输出,并在等待输入之前关闭文件。在那之后,它每次都有效,但我无法解释所有事情。

fclose(fp);
fclose(ireland);
fclose(mmplus);
printf("The total population of all the cities is %d.\n",total_pop);
getchar();
return 0;

答案 1 :(得分:0)

这是实现算法的一种方法

//note: the system function: perror()
//      outputs the strerror() message,
//      the first parameter text, etc

//Program that filters and processes data with fgets() and sscanf()
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // strcpy(), strlen()
#include <unistd.h> // unlink()

int main()
{
    FILE *fp      = NULL; // input
    FILE *ireland = NULL; // list irish cities
    FILE *mmplus  = NULL; // list cities > 1million population

    int pop;
    char country[50];
    char city[50];

    int total_pop=0;
    int  maxPopulation = 0;
    char maxPopulationCity[50] = {'\0'};
    char maxPopulationCountry[50] = {'\0'};

    char buffer[200]; // input work area


    if( NULL == (fp = fopen("population.txt","r") ) )
    { // then, fopen failed
        perror( "fopen for population.txt failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    if( NULL == (ireland = fopen("ireland_pop.txt","w") ) )
    { // then, fopen failed
        perror( "fopen for ireland_pop.txt failed" );
        fclose(fp); // cleanup
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful

    if( NULL == (mmplus = fopen("greater_than_1MM.txt","w") ) )
    { // then, fopen failed
        perror( "fopen for greater_than_1MM.txt failed" );
        fclose(fp); // cleanup
        fclose(ireland);
        unlink("ireland_pop.txt");
        exit( EXIT_FAILURE );
    }

    // implied else, fopen successful


    //Scanning fp row by row
    while ( fgets( buffer, sizeof buffer, fp ) )
    {
        // this code makes the following assumptions
        // 1) city is all one word
        //    (I.E, no 'st paul'
        // 2) country is all one word and 'ireland' is always lower case
        //    (I.E. no 'Ireland' and no 'United States'
        // 3) pop contains no ',' and is always positive
        // 4) data item delimiters are only ' ', \t

        if( 3 != sscanf(buffer, " %s %s %i", country, city , &pop) )
        {
            //calculate the total population
            total_pop += pop;

            //Storing the highest pop found so far
            if (pop >maxPopulation)
            {
                maxPopulation=pop; // save new largest population
                strcpy( maxPopulationCity, city ); // save new city
                strcpy( maxPopulationCountry, country ); // save new country
            }//End if

            //Finding 1 million+ cities
            if(pop>=1000000)
            {
                fprintf(mmplus,"%s %s %d\n",country,city,pop);
            }//End if

            //If the city is in Ireland
            if (strcmp("ireland",country) == 0)
            {
                fprintf(ireland,"%s %s %d\n",country,city,pop);
            }//End if

            if( buffer[strlen(buffer)-1] != '\n' )
            { // then, input line to long for buffer[]
                // read chars until newline consumed
                while( '\n' != getchar() ) ;
            }// end if
        } // end if
    }//End while

    printf("The city with the highest population is %s, %s, with a population of %d",
           maxPopulationCity,
           maxPopulationCountry,
           maxPopulation);

    printf("The total population of all the cities is %d.",total_pop);
    getchar();

    fclose(fp);
    fclose(ireland);
    fclose(mmplus);
    return(0);
} // end function: main