繁体   English   中英

在没有 malloc 和 c 的 arrays 中保存文件

[英]saving file in arrays without malloc with c

我有一个作业,我需要从文件中读取并保存在 arrays 信息中,例如城市名称、国家代码、县名和人口

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

int main () 
{
    struct Country
    {
       char name [100];   // Le nom ASCII
       char code[100]; // Le code de deux lettres
   };

   //const struct Pays PAYS_BIDON = {"??", "??"};
   
   struct City
   {
       char name[100]; // Le nom ASCII
       long population;          // La population
       struct Country country;          // Le pays de la ville
   };
    struct City city;
    FILE* fp = fopen("fich.txt", "r");
 
    if (!fp)
    {
        printf("Can't open file\n");
    }
    else 
    {
        char buffer[1024];
        while (fgets(buffer, 1024, fp))
        {
            int i =0;
            char* value = strtok(buffer, "\t");
            while (value) 
            {
                strcpy(city.name,value);
                value = strtok(NULL, "\t");
                printf("name : %s\n", city.name);
              
            }
            
        }
        fclose(fp);
    }
    return 0;

} 

直到这里我的代码正在工作,但是当我尝试读取国家名称时它不起作用:

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

int main () 
{
    struct Country
    {
       char name [100];   // Le nom ASCII
       char code[100]; // Le code de deux lettres
   };

   //const struct Pays PAYS_BIDON = {"??", "??"};
   
   struct City
   {
       char name[100]; // Le nom ASCII
       long population;          // La population
       struct Country country;          // Le pays de la ville
   };
    struct City city;
    FILE* fp = fopen("fich.txt", "r");
 
    if (!fp)
    {
        printf("Can't open file\n");
    }
    else 
    {
        char buffer[1024];
        while (fgets(buffer, 1024, fp))
        {
            int i =0;
            char* value = strtok(buffer, "\t");
            while (value) 
            {
                strcpy(city.name,value);
                value = strtok(NULL, "\t");
                printf("city name : %s\n", city.name);
                strcpy(city.country.name,value);
                value = strtok(NULL, "\t");
                printf("country : %s\n", city.country.name);
                
            }
            
        }
        fclose(fp);
    }
    return 0;

} 

文件中的数据是这样的:

3040051 les Escaldes    les Escaldes    Ehskal'des-Ehndzhordani,Escaldes,Escaldes-Engordany,Les Escaldes,esukarudesu=engorudani jiao qu,lai sai si ka er de-en ge er da,Эскальдес-Энджордани,エスカルデス=エンゴルダニ教区,萊塞斯卡爾德-恩戈爾達,萊塞斯卡爾德-恩戈爾達    42.50729    1.53414 P   PPLA    AD      08              15853       1033    Europe/Andorra  2008-10-15
3041563 Andorra la Vella    Andorra la Vella    ALV,Ando-la-Vyey,Andora,Andora la Vela,Andora la Velja,Andora lja Vehl'ja,Andoro Malnova,Andorra,Andorra Tuan,Andorra a Vella,Andorra la Biella,Andorra la Vella,Andorra la Vielha,Andorra-a-Velha,Andorra-la-Vel'ja,Andorra-la-Vielye,Andorre-la-Vieille,Andò-la-Vyèy,Andòrra la Vièlha,an dao er cheng,andolalabeya,andwra la fyla,Ανδόρρα,Андора ла Веля,Андора ла Веља,Андора ля Вэлья,Андорра-ла-Велья,אנדורה לה וולה,أندورا لا فيلا,አንዶራ ላ ቬላ,アンドラ・ラ・ヴェリャ,安道爾城,안도라라베야 42.50779    1.52109 P   PPLC    AD      07              20430       1037    Europe/Andorra  2020-03-03
290594  Umm Al Quwain City  Umm Al Quwain City  Oumm al Qaiwain,Oumm al Qaïwaïn,Um al Kawain,Um al Quweim,Umm Al Quwain City,Umm al Qaiwain,Umm al Qawain,Umm al Qaywayn,Umm al-Quwain,Umm-ehl'-Kajvajn,Yumul al Quwain,am alqywyn,mdynt am alqywyn,Умм-эль-Кайвайн,أم القيوين,مدينة ام القيوين 25.56473    55.55517    P   PPLA    AE      07              62747       2   Asia/Dubai  2019-10-24

我需要从第一行

     city.name = les Escaldes ;
     city.country.code = AD;
     city.population = 15853;

我需要从第二行

     city.name = Andorra la Vella;
     city.country.code = AE;
     city.population = 20430;

我需要从第三行

     city.name = Umm Al Quwain City;
     city.country.code = AD;
     city.population = 62747;

所以我不知道我做错了什么或做正确的事

几个问题...

  1. 您正在使用您的struct (例如) struct City city;单个实例; . 因此,当您阅读第二行时,您会覆盖/删除第一行的数据。

  2. 你需要一个结构数组。

  3. 而且,虽然它合法的,但在function scope 处定义结构并不是非常有用。 如果您决定将 function 拆分为多个,则其他的将没有结构定义。 最好在文件scope 中定义它们,以便所有函数都可以使用它们。

  4. 您同时使用city.name和 city- city->name 只有一个是正确的。

  5. while (value)循环不能按您的意愿工作。

  6. 此外,您没有填写结构的所有字段。

这是一个重构版本:

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

struct Country {
    char name[100];                 // Le nom ASCII
    char code[100];                 // Le code de deux lettres
};

struct City {
    char name[100];                 // Le nom ASCII
    long population;                // La population
    struct Country country;         // Le pays de la ville
};

// NOTE: need array of structs
struct City citylist[100];

int
main(void)
{
    struct City *city;

    FILE *fp = fopen("fich.txt", "r");
    if (! fp) {
        printf("Can't open file -- %s\n",strerror(errno));
        exit(1);
    }

    char buffer[1024];

    int count = 0;
    char *value;

    // load up file contents
    while (fgets(buffer, sizeof(buffer), fp)) {
        city = &citylist[count++];

        value = strtok(buffer, "\t\n");
        strcpy(city->name,value);

        value = strtok(NULL, "\t\n");
        city->population = atol(value);

        value = strtok(NULL, "\t\n");
        strcpy(city->country.name,value);

        value = strtok(NULL, "\t\n");
        strcpy(city->country.code,value);
    }

    fclose(fp);

    // print data
    for (int i = 0;  i < count;  ++i) {
        city = &citylist[i];
        printf("City: %s, population %ld, Country: %s (Code %s)\n",
            city->name,city->population,
            city->country.name,city->country.code);
    }

    return 0;
}

请注意,我已经定义了一个任意固定大小的数组citylist 但是,拥有一个动态数组要灵活得多。 有关它的实现,请参阅我的答案: 在 C 中创建动态字符串数组

暂无
暂无

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

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