#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "queue.h"
#include "stack.h"
#define NAME_SIZE 20
#define RECORDS_SIZE 100

typedef struct
{
    char studName[20];
    int timeEnter;
    int timeUpdate;
}STUDENT;
typedef struct
{
    char tutorName[NAME_SIZE];
    int tutorTime;
    STUDENT *ptr;
}TUTOR;
QUEUE *queue1;
STACK *stack1;

void getData(STUDENT *studArr[], TUTOR tutorArr[1]);

int main(void)
{
    STUDENT *studArr[RECORDS_SIZE];
    TUTOR tutorArr[1];
    getData(studArr, tutorArr);
    return 0;
}
void getData(STUDENT *studArr[], TUTOR tutorArr[1])
{
    FILE *fp;
    char fileName[NAME_SIZE];
    char buffer[RECORDS_SIZE];
    int first;
    int count = 0;
    printf("Enter the file name: ");
    gets(fileName);
    fp = fopen(fileName, "r");
    if (fp == NULL)
    {
    printf("Error opening file!\n");
    return;
    }
    fscanf(fp, "%d", &first);
    *studArr = (STUDENT*)malloc(first*sizeof(STUDENT));
    if(studArr == NULL)
        exit(EXIT_FAILURE);
    while(fgets(buffer, RECORDS_SIZE, fp) != NULL)
    {

        if(count < first)
        {
            sscanf(buffer, "%[^,],%d", (*studArr)[count].studName, &(*studArr)[count].timeEnter);
            printf("%s,%d\n", (*studArr)[count].studName, (*studArr)[count].timeEnter);
        }

        else 
        {
            sscanf(buffer, "%s", tutorArr[0].tutorName);
            printf("%s\n", tutorArr[0].tutorName);
        }

        count++;
    }
    return;
 }

Hi, I'm trying to read data from file to structure members, the code seems to work but when I print out strings, the first line output garbage and the rest is according to what the program should do. why does the first line output garbage? also the first line was not intended to be print out. This is my output:

Enter the file name: in.txt

,-842150451
A,10
B,12
C,60
D,120
tutorY
Press any key to continue . . .

post the first few lines of the data file, if small enough just post the whole thing.

if(count < first)

That looks backwards, first is initialized to 0 and count is read from the file. The only way count could be less than first is if the value in the file is a negative number.

i meant if(count <= first)

i will edit that part and post the file data as well
also first is not 0 first was the first number of the file which is 4

Edited 3 Years Ago by bluekb

i think that this is because of the fscanf fucntion reading the first number and leave the \n at the end of the line for fgets to read

if I let count < first then for some reason my else statement output

D,120
tutorY

but i only want
tutorY not
D,120

This question has already been answered. Start a new discussion instead.