简体   繁体   English

将文本文件读入结构数组C

[英]Reading text file into array of structures C

I have been stuck in trying to read this text file into array of structures.Here is a few lines from the text. 我一直试图将这个文本文件读入结构数组中。这里有几行文字。

A|Boston Red Sox|Fenway Park|4 Yawkey Way|Boston|MA|02215|(617) 267-9440|redsox.com
N|St. Louis Cardinals|Busch Stadium|700 Clark Street|St. Louis|MO|63102|(314) 345-9600|cardinals.com

Here is the array of structures. 这是结构的数组。 I modified the text file so it only contains league and team name to make it easier to test changes. 我修改了文本文件,使其仅包含联赛和球队名称,以便于测试更改。

#define LEN_LINE 80
#define LEN_NAME 30
#define MAX_LINES 60
#define LEAGUE_NAME 5

typedef struct
{
    char leagueName[LEAGUE_NAME + 1];
    char teamName[LEN_NAME + 1];


} team_t;

Here is where the problem lies.I have tried implementing strncpy() though being a beginner it has been hard trying to use the function correctly in this scenario. 这是问题所在。尽管我是初学者,但我尝试实现strncpy()很难在这种情况下正确使用该函数。

FILE * filePtr;
    int index, count;
    char line[LEN_LINE + 1];
    team_t teams[MAX_LINES];
    filePtr = fopen("MLBteams.txt", "r");
    if(filePtr == NULL)
    {
        printf("Unable to open file.\n");
    }
    else
    {
        index = 0;
        while(index<MAX_LINES && fgets(line, LEN_LINE, filePtr))
        {
            if(2 == sscanf(line,"%s %s", teams[index].leagueName, teams[index].teamName)

               )
            {
                index++;
            }
        }
        fclose(filePtr);  

I looked through other threads though they've only confused me. 我浏览了其他线程,尽管它们只是让我感到困惑。

From your example of the content of the text file, you have a splitter as | 在您的文本文件内容示例中,您有一个|分隔符。 symbol ( A|Boston Red Sox ). 符号(A | Boston Red Sox)。 You need to put it inside sscanf: 您需要将其放入sscanf中:

if(2 == sscanf(line,"%s|%s", teams[index].leagueName, teams[index].teamName))
{
                index++;
}

Ok. 好。 Since there are spaces in your strings, you can parse manually its not hard. 由于字符串中有空格,因此您可以手动解析它,并不难。 Instead of code abow do this: 代替下面的代码:

char *league_p = strchr(line,'|');
int len = league_p - line;
char *league = calloc(len, 1);
memcpy(league,line,len - 1);
league_p++;
char *team_p = strchr(league_p,'|');
len = team_p - league_p;
char *team = calloc(len, 1);
memcpy(team,league_p,len - 1);

This way you will always get first two values splitted 这样,您将始终获得前两个值的拆分

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

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