从文件读取到C

时间:2017-10-24 04:09:29

标签: c arrays

人。 我无法从C中的文件读取并放入数组,将数组的每个部分分配给变量。

该文件如下所示:

A0005:Burger:2.39:Extra Cheese
A0006:Soda:1.35:Coke
....

问题是,当你到达冒号时,我不知道如何在C中拆分字符串。

到目前为止,我试图制作一个结构,尝试使用strtok和getchar,但到目前为止还没有成功。

这是我到目前为止所得到的

#include <stdio.h>

struct menuItems{
 char itemCode[5];
 char itemName[50];
 float itemPrice;
 char itemDetails[50];
 };


int main(void){
    FILE *menuFile;
    char line[255];
    char c;

    struct menuItems allMenu = {"","",0.0,""};


    if ((menuFile = fopen("addon.txt", "r")) == NULL){
        puts("File could not be opened.");

    }
    else{
        printf("%-6s%-16s%-11s%10s\n", "Code", "Name", "Price", "Details");
        while( fgets(line, sizeof(line), menuFile) != NULL ){
            c = getchar();
            while(c !='\n' && c != EOF){
                fscanf(menuFile, "%5s[^:]%10s[^:]%f[^:]%s[^:]", allMenu.itemCode, allMenu.itemName, &allMenu.itemPrice, allMenu.itemDetails);
            }

            }


    }
}

1 个答案:

答案 0 :(得分:1)

对于您需要执行以下操作的每一行:

   /* your code till fgets followed by following */
   /* get the first token */
   token = strtok(line, ":");

   /* walk through other tokens */
   while( token != NULL ) {
      printf( " %s\n", token ); /* you would rather store these in array or whatever you want to do with it. */

      token = strtok(NULL, ":");
   }

以下代码为100个menuItems的数组分配内存,并将给定的文件条目读入其中。您实际上可以计算输入文件中的行数并分配尽可能多的条目(而不是硬编码100):

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

struct menuItem
{
    char itemCode[5];
    char itemName[50];
    float itemPrice;
    char itemDetails[50];
};

int main()
{
    char line[255];
    FILE *menuFile = fopen("addon.txt", "r");
    struct menuItem * items =
        (struct menuItem *) malloc (100 * sizeof (struct menuItem));
    struct menuItem * mem = items;

    while( fgets(line, sizeof(line), menuFile) != NULL )
    {
        char *token = strtok(line, ":");
        assert(token != NULL);
        strcpy(items->itemCode, token);
        token = strtok(NULL, ":");
        assert(token != NULL);
        strcpy(items->itemName, token);
        token = strtok(NULL, ":");
        assert(token != NULL);
        items->itemPrice = atof(token);
        token = strtok(NULL, ":");
        assert(token != NULL);
        strcpy(items->itemDetails, token);
        items++;
   }

   free(mem);
   fclose(menuFile);
}