I have a struct of students that written to a file all what i want is intial the array with values from the file using any method , the aim is to put the struct values into array to help sorting process the code gives me punch an kick any idea how to achive it

    #include <stdio.h>
    #include <string.h>
    #include <conio.h>
    #include <stdlib.h>
    #include <windows.h>
    struct student
     {
      char  id[5];
      char  name[30];
      int   term;
      float gpa;
      char  grade;
     };

    struct student stu;

    typedef struct student stud;


    int main ()
    {
    FILE *fp;
    fp = fopen("record.txt","ab+");
    char nextChar = getc(fp);
    int numCharacters = 0;

    while (nextChar != EOF)
    {
        numCharacters++;
        nextChar = getc(fp);
    }
    //////// detect number of characters ////////

    int chunck = numCharacters/sizeof(stu);

    stud *arr = (stud *)malloc(chunck);

    /*//problem comes next ...
    // intial the array of students with records from file
    while(fread(&stu,sizeof(stu),1,fp) == 1)
    { 
      for(d=0;d<chunck;d++)
      {
       arr[d].id=stu.id;
       arr[d].name=stu.name;
       arr[d].term=stu.term;
       arr[d].gpa=stu.gpa;
      }     
    }*/

    return 0;
    }

You need to post a couple lines from the file so we can see how it is formatted. But generally you would want to read each field into it's appropriate structure element. The easiest way to do it is calling fscanf() instead of reading the file one character at a time like you are trying to do.

For example, it might be read something like this:

     FILE* fp = fopen("students.txt","r");
     struct student st;
     struct student starray[100];
     int numStudents = 0;

     while( fscanf(fp,"%s%s%d%f%c",st.id,st.name,&st.term,&st,gpa,&st.grade) > 0)
     {
          starray[numStudents++] = st;
     }

But, of course, the above may be all wrong, depending on how the file was written.

the file lines is a miss its one line , all records are on one line i have determined the records throw the sizeof(stu)

example : 1 mohamed talaat €@A 2 ahmed mohamed @A

when i have tried the code the data comes out of the array as junk data

How did you write the records? Did you use fwrite()? If you did, then just use fread(). The parameters to fread() are the same as fwrite()

struct student students[100];
int count = 0;

while( fread(&students[count],sizeof(struct student),1,fp) == 1 )
   count++;

// Another way of doing it is to attempt to read them all at one time
// fread() will return the number of student records actually read.

count = fread(students,sizeof(struct student),100,fp);

Thanks ancient dragon for your concern
i tried this but a junk data still comes out

this is all the code take a look on the sortstudents() functions

#include <stdio.h>
#include <string.h>
#include <conio.h>
#include <stdlib.h>
#include <windows.h>
///////////////////////////////////////////////////////////////////////////
struct student
 {
  char  id[5];
  char  name[30];
  int   term;
  float gpa;
  char  grade;
 };

struct student stu;

typedef struct student stud;


//////////////////////////////////////////////////////////////////////////
//set the cordinate to 0, 0 (top-left corner of window)
//<windows.h> is needed
COORD coord = {0,0};
//////////////////////////////////////////////////////////////////////////
//need cordinate struct to use it
//gotoxy to set coordinate x,y
void gotoxy(int x, int y)
{
//X and Y coordinates 
  coord.X = x; coord.Y = y;
// ew3a tensa Microsoft 
  SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
//////////////////////////////////////////////////////////////////////////
//print regtangle shape Ascii table www.asciitable.com
// window width = 80 character window hight = 25 character
void drawRectangle()
{
 int i, j;
//print the corner rear top left 
 gotoxy(0,0);    
 printf("%c",201);
// print 78 line shape = starts from rear top left ended at the top rear right     
 for(i = 1; i < 78; i++)
  {
   gotoxy(i, 0);
   printf("%c",205);
  }
//print the corner rear top right
 gotoxy(78,0);    
 printf("%c",187);
//print the corner rear right side with width = 25
 for(i = 1; i < 25; i++)
  {
   gotoxy(78, i);
//print T-shape at width 6 and after 6 proceed until 25 printing right side 
   if(i == 6)
    {
     printf("%c",185);
    }
   else
    {
     printf("%c",186);
    }
  }
//print the corner rear bottom right
 gotoxy(78, 25);
 printf("%c",188);
// -i- already = 78
// print bottom side pf the regtangle
for(i = 77; i > 0; i--)
 {
  gotoxy(i,25);
// print T-shape at width 35 and after that proceed until 78 printing rgt base side 
 if(i == 35)
  {
   printf("%c",202);
  }
 else
  {
   printf("%c",205);
  }
 }
//print the corner rear bottom left
  gotoxy(0,25);
  printf("%c",200);
// print T-shape at width 6 and after 6 proceed until 25 printing left side     
 for(i = 24; i > 0; i--)
  {
   gotoxy(0,i);
   if(i == 6)
    {
     printf("%c",204);
    }
   else
    {
     printf("%c",186);
    }
   }
// print T-shape at width 36 and connect left side to right side
 for(i = 1; i < 78; i++)
  {
   gotoxy(i,6);
   if(i == 35)
    {
     printf("%c",203);
    }
    else
    {
     printf("%c",205);
    }
  }
// connect middle T-shape at the middle of the regtangle to the base
 for(i = 7; i < 25; i++)
  {
   gotoxy(35,i);
   printf("%c",186);
  }
}
//////////////////////////////////////////////////////////////////////////
// Build Program window interface using functions --drawRectangle 
// with color 1 = Blue & Font color 7 = White
void swindow()
{
 int i;
 drawRectangle();
 gotoxy(28,1);
 system("color 17");
 printf("STUDENT GRADE SYSTEM");
 gotoxy(28,2);
 for(i=1;i<21;i++)
 {
  printf("%c",205);
 }
 gotoxy(15,3);
 printf("College of Computing and Information Technology");
 gotoxy(10,4);
 printf(" ");
 gotoxy(10,5);
 printf("Arab Academy for Science, Technology & Maritime Transport");
 gotoxy(25,24);
}
//////////////////////////////////////////////////////////////////////////
void print_heading(const char st[])
{
 gotoxy(50,8);
 printf("%s",st);
}
//////////////////////////////////////////////////////////////////////////
void clearWindow()
{
    int i,j;
    for(i = 37; i < 78; i++)
     {
        for(j = 7; j < 25; j++)
        {
           gotoxy(i,j);
           printf(" ");
        }
    }
}
//////////////////////////////////////////////////////////////////////////



//////////////////////////////////////////////////////////////////////////
void add()
{
    clearWindow();
    print_heading("Add Record");
    int print = 37;
    char ans;
    int i;
    FILE *fp;
    fp = fopen("record.txt","ab+");
    if(fp == NULL)
    {
     MessageBox(0,"Error in Opening file\nMake sure your file is not write protected","Warning",0);
    }
    else
    {
     fflush(stdin);
//here i can Add  Records ... 
//////////////////////////////////////////////////////////////////////////////// 
     gotoxy(print,10);printf("ID: ");gets(stu.id);
     gotoxy(print,12);printf("Name: ");gets(stu.name);
     gotoxy(print,14);printf("Term: ");scanf("%d",&stu.term);
     gotoxy(print,16);printf("Score % : ");scanf("%f",&stu.gpa);

     if (stu.gpa>=3.40)
      {
       stu.grade='A';
      }
     else {
           if (stu.gpa>=2.80)
            {stu.grade='B';}
           else
           {
            if (stu.gpa>=2.20)
             {stu.grade='C';}
            else
            {
             if (stu.gpa>=2.00)
              {stu.grade='D';}
             else
             {stu.grade='F';}
             }
           }
          }
     gotoxy(print,18);printf("GPA: %c",stu.grade);printf("\n");

     gotoxy(print,20);printf("Press(Y) to Save (N) for Cancel... ");//scanf("%c",&ans);
     ans = getche();   

     if (ans=='y' || ans=='Y')
     {
      fwrite(&stu, sizeof(stu), 1, fp);
      gotoxy(40,22); printf("The record is sucessfully added");
     }
     else 
     {
      gotoxy(40,22); printf("Entry process cancelled");
     }
    }
    fclose(fp);
}
//////////////////////////////////////////////////////////////////////////
void search(){
    clearWindow();
    print_heading("Search Record");

    char s_id[5];

    int isFound = 0;

    gotoxy(37,10);

    printf("Enter ID to Search: ");

    fflush(stdin);

    gets(s_id);
 //Read the record file from File
    FILE *fp;
    fp = fopen("record.txt","ab+");
    while(fread(&stu,sizeof(stu),1,fp) == 1)
    {
        if(strcmp(s_id,stu.id) == 0)
        {
         isFound = 1;
         break;
        }
    }
    if(isFound == 1){
        gotoxy(37,12);printf("The record is Found");
        gotoxy(37,13);printf("--------------------");
        gotoxy(37,14);printf("ID: %s",stu.id);
        gotoxy(37,16);printf("Name: %s",stu.name);
        gotoxy(37,18);printf("Term: %d",stu.term);
        gotoxy(37,20);printf("Score %: %0.1f",stu.gpa);
        gotoxy(37,22);printf("GPA: %c",stu.grade);
    }else
    {
     gotoxy(37,12);printf("Sory, No record found in the database");
    }
    fclose(fp);
}
//////////////////////////////////////////////////////////////////////////
void sortstudents()
{
 clearWindow(); 
 FILE *fp;
    fp = fopen("record.txt","r");

//////// detect number of characters ////////
char nextChar = getc(fp);
int numCharacters = 0;

while (nextChar != EOF)
{
    //Do something else, like collect statistics
    numCharacters++;
    nextChar = getc(fp);
}
//////// detect number of characters ////////

int chunck = numCharacters/sizeof(stu);

//stud *arr = (stud *)malloc(chunck);
stud starray[25];

int count = 0;
//while( fread(&starray[count],sizeof(stu),1,fp) == 1 )
//   count++;

// Another way of doing it is to attempt to read them all at one time
// fread() will return the number of student records actually read.

count = fread(starray,sizeof(stu),100,fp);



  gotoxy(37,12);printf("The record is Found");
  gotoxy(37,13);printf("--------------------");
  gotoxy(37,14);printf("ID: %s",starray[0].id);
  gotoxy(37,16);printf("Name: %s",starray[0].name);
  gotoxy(37,18);printf("Term: %d",starray[0].term);
  gotoxy(37,20);printf("Score %: %0.1f",starray[0].gpa);
  gotoxy(37,22);printf("GPA: %c",starray[0].grade);


     /*"ID: %s",stu.id);
     "Name: %s",stu.name);
     "Term: %d",stu.term);
     Score %: %0.1f",stu.gpa);
     "GPA: %c",stu.grade);*/            

fclose(fp);

}
//////////////////////////////////////////////////////////////////////////
void menu(){
    int choice;
    int x = 2;
    while(1)
    {
     gotoxy(x,10);
     printf("1. Add Student");
     gotoxy(x,12);
     printf("2. Search Student");
     gotoxy(x,14);
     printf("3. Statistics");
     gotoxy(x,16);
     printf("4. Close");
     gotoxy(x,20);
     printf("Please enter your choice :");
     scanf("%d",&choice);

    switch(choice)
     {
      case 1:
       add();
      break;

      case 2:
       search();
      break;

      case 3:
       sortstudents();
      break;

      case 4:
       exit(0);
      break;

      default:
       break;
        }
    }
}
//////////////////////////////////////////////////////////////////////////
int main()
{
// draw entry window
//drawRectangle();
swindow();
menu();
//clearWindow();
 system("PAUSE");   
 return 0; 
}

i have posted the whole project am stucked with this problem and cannot find a way to get out of it or turn around it ... i have to load the record into array to be able to sort it by gpa

line 300: The file pointer is at EOF when that line is reached because of lines 277-288: there is no need for that loop so just delete it. Besides, there is a lot easier way to get the number of characters in the file. But that function doesn't need to know how big the file is.

After making the changes I mentioned, that function should look like this:

void sortstudents()
{
    clearWindow();
    FILE *fp;
    fp = fopen("record.txt", "r");


    //stud *arr = (stud *)malloc(chunck);
    stud starray[25];

    int count = fread(starray, sizeof(stu), 100, fp);
    fclose(fp);


}

Note that the array is local to that function, so it will get destroyed immediately when the function terminates. If you need the sorted array somewhere else in your program then you will have to pass it as a parameter into the function instead of declaring it locally.

The next think I suppose you need to do is sort the array. There are a lot of sort algorithms, some more difficult than the others. I'd suggest you use the bubble sort algorithm becaue it's the easiest to code. You can easily find it by googling for "bubble sort algorithm".

still got strange junk when am try to print data out of the array
do you think there is somthing wrong at the print

void sortstudents()
{
 clearWindow();
    FILE *fp;
    fp = fopen("record.txt", "r");

    //stud *arr = (stud *)malloc(chunck);
    stud starray[25];

    int count = fread(starray, sizeof(stu), 100, fp);
    fclose(fp);



  gotoxy(37,12);printf("The record is Found");
  gotoxy(37,13);printf("--------------------");
  gotoxy(37,14);printf("ID: %i",*starray[0].id);
  gotoxy(37,16);printf("Name: %s",starray[0].name);
  gotoxy(37,18);printf("Term: %d",starray[0].term);
  gotoxy(37,20);printf("Score %: %0.1f",starray[0].gpa);
  gotoxy(37,22);printf("GPA: %c",starray[0].grade);


     /*"ID: %s",stu.id);
     "Name: %s",stu.name);
     "Term: %d",stu.term);
     Score %: %0.1f",stu.gpa);
     "GPA: %c",stu.grade);*/            

fclose(fp);

}

thank you again for your help ... am very greatful for your concern

i think the array is not intialized so how could i intialize it

this one works as expected.

void sortstudents()
{
    clearWindow();
    FILE *fp;
    fp = fopen("record.txt", "r");
    if (fp != NULL)
    {

        //stud *arr = (stud *)malloc(chunck);
        stud starray[25] = { 0 };

        int count = 0;
        while (fread(&starray[count], sizeof(stu), 1, fp) > 0)
            count++;
        fclose(fp);

        gotoxy(37, 12); printf("The record is Found");
        gotoxy(37, 13); printf("--------------------");
        gotoxy(37, 14); printf("ID: %i", *starray[0].id);
        gotoxy(37, 16); printf("Name: %s", starray[0].name);
        gotoxy(37, 18); printf("Term: %d", starray[0].term);
        gotoxy(37, 20); printf("Score %: %0.1f", starray[0].gpa);
        gotoxy(37, 22); printf("GPA: %c", starray[0].grade);
    }
}

your the best .... :) it is works very fine and well

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.