Home > Mobile >  Using "fsgets" in C How can Split string and make a structure
Using "fsgets" in C How can Split string and make a structure

Time:05-07

i want to read from the file using fgets and send the information to struct in array so i write this code but the output in incorrect

this is the file i tried to read

1#18042022#14:30#Birzeit#Ramallah#6#15
2#18042022#11:45#Birzeit#Birzeit#6#1
13#19042022#14:30#Birzeit#Atara#6#20
53#20042022#14:00#Birzeit#Nablus#6#7

I have written the following code in attempt to fill an array of struct bus:

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

typedef struct bus
{
    int busnumber;
    char* traveldate;
    char* traveltime;
    char* fromdestination;
    char* todestination;
    float price;
    int capacity;

}bus;

int main()
{
    bus busses[numberofbuses("busses.txt")];
    FILE *fp;
    fp = fopen("busses.txt" , "r");
    char line_data[10240];
    int i = 0;
    char c;
   while(fgets(line_data,10240, fp))
    {
        printf("%s\n",line_data);
    busses[i].busnumber = atoi(strtok(line_data,"#"));
    busses[i].traveldate = strtok(NULL,"#");
    busses[i].traveltime = strtok(NULL,"#");
    busses[i].fromdestination = strtok(NULL,"#");
    busses[i].todestination = strtok(NULL,"#");
    busses[i].price = atof(strtok(NULL,"#"));
    busses[i].capacity = atoi(strtok(NULL,"#"));
    i  ;
    }
printf("%s\n",busses[0].traveldate);
    for (int j = 0 ; j < numberofbuses("busses.txt") ; j  )
    {
        printf("%d %s %s %s %s %f %d\n", busses[j].busnumber,busses[j].traveldate,busses[j].traveltime,busses[j].fromdestination,busses[j].todestination , busses[j].price, busses[j].capacity);
    }

   fclose(fp);
   return(0);
}
int numberofbuses (char *filename)
{
    FILE *fp;
    char c;
    int count = 0;
    fp = fopen(filename,"r");
    if(fp == NULL)
    {
        perror("Error opening file");
        return(-1);
    }
    else
    {
        for (c = getc(fp); c != EOF; c = getc(fp))
            if (c == '\n')
                count = count   1;
        return count;
    }
}

CodePudding user response:

It is a cool idea to read the entire file as a single string to be tokenized, but it does add a little complexity to reading it. Things work just as nicely with the strdup() option.

User input is always a total pain, but in your case it can be done fairly simply. You have to build the proper tools though:

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


typedef struct bus
{
    int    busnumber;
    char * traveldate;
    char * traveltime;
    char * fromdestination;
    char * todestination;
    float  price;
    int    capacity;
} bus;


bool read_string( FILE * f, char ** s )
{
    char buf[100] = {0};
    if (fscanf( f, "           
  •  Tags:  
  • c
  • Related