Thread: Bubble use , read from file then write to another filed as bubble.

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    151

    Bubble use , read from file then write to another filed as bubble.

    Hi ,
    This is a program I have been trying to read some names and points for those names from a file , then array the names based on their points and write them to another text file . I may have done a terrible work , I am sorry If I did.

    Code:
    #include <stdio.h> 
    #include <string.h>
    typedef struct kayit {
    		char s[40];
    	} KAY;
    	KAY k[10];
    void sirala(int *,int,struct kayit *);
    
    int main() {
    FILE *fp;
    fp=fopen("d.txt","r");
    struct kayit {
    		char s[40];
    	};
    	struct kayit k[10];
    	int i=0;
    	while(fgets(k[i].s,20,fp)!=NULL)
    	 i++;
    	int x=i-1;
    char *p;
    	
    	int c[40];
    	for(i=0;i<=x;i++) {
    		p=strpbrk(k[i].s,"0123456789");
    		sscanf(p,"%d",&c[i]);
    	 printf("%d\n",c[i]);
    		}
    	fclose(fp);
    sirala(c,x+1,k);
    	printf("%s\n%s\n",k[0].s,k[1].s);
    	fp=fopen("sonuc.txt","w");
    	
    	
    	for(i=0;i<=x;i++) {
    	
    		fprintf(fp,"%s",k[i].s); }
    
    
    
    
    
    
    
    	return 0;
    }
    	
    	
    	
    	
    	
    	
    	
    	
    	
    
    	void sirala(int *d,int y,struct kayit *i) {
     int say,tur,tut;
    		
    		for(tur=0;tur<y-1;tur++) {
    			for(say=0;say<y;say++) {
    				if(d[say]>d[say+1]) {
                                 tut=d[say];
    						d[say]=d[say+1];
    						d[say+1]=tut; 
    				KAY gecici =i[say];
    				i[say]=i[say+1];
    				i[say+1]=gecici;
    				}
    				}}
    		}
    Also variable names are turkish , I havent changed them , I hope those dont confuse anyone . Thank you for your help , If I couldnt tell the aim of problem here I will try it again :
    For example a text file :

    Alex 90
    Roberto 70
    Elisha 60

    The program will make the text like this :

    Elisha 60
    Roberto 70
    Alex 90

  2. #2
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    Sorry guys , I didnt mean to show you my codes . I forgot to say that they dont work =) . I would be glad if you work on them..

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Well you can start by having a consistent approach to indentation, and general code layout skills. Simply finding your way around the code is far too hard otherwise.
    Code:
    #include <stdio.h>
    #include <string.h>
    typedef struct kayit {
        char s[40];
    } KAY;
    KAY k[10];
    void sirala(int *, int, struct kayit *);
    
    int main()
    {
        FILE *fp;
        fp = fopen("d.txt", "r");
        struct kayit {
            char s[40];
        };
        struct kayit k[10];
        int i = 0;
        while (fgets(k[i].s, 20, fp) != NULL)
            i++;
        int x = i - 1;
        char *p;
    
        int c[40];
        for (i = 0; i <= x; i++) {
            p = strpbrk(k[i].s, "0123456789");
            sscanf(p, "&#37;d", &c[i]);
            printf("%d\n", c[i]);
        }
        fclose(fp);
    
        sirala(c, x + 1, k);
    
        printf("%s\n%s\n", k[0].s, k[1].s);
    
        fp = fopen("sonuc.txt", "w");
        for (i = 0; i <= x; i++) {
            fprintf(fp, "%s", k[i].s);
        }
    
        return 0;
    }
    
    void sirala(int *d, int y, struct kayit *i)
    {
        int say, tur, tut;
    
        for (tur = 0; tur < y - 1; tur++) {
            for (say = 0; say < y; say++) {
                if (d[say] > d[say + 1]) {
                    tut = d[say];
                    d[say] = d[say + 1];
                    d[say + 1] = tut;
                    KAY gecici = i[say];
                    i[say] = i[say + 1];
                    i[say + 1] = gecici;
                }
            }
        }
    }
    The first thing, shouldn't your struct kayit contain both a string and an integer, to reflect your input file?
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  4. #4
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    Do you mean that my struct has to have an integer to take the point of "ALEX" for example? If you do , no. I can all save those into a string then drain the numbers by strpbrk and then transfer to an integer array.That is what I am doing. But somehow ,there is something wrong with the codes.

  5. #5
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    Sorry for the unnecessery post I found the problem. I copied struct decleration out of the main function , but I forgot the old one in the function without deleting. I think I am forgeting too much ; maybe you can tell what my problem is with my brain??? =) Take care..

  6. #6
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Code:
    typedef struct kayit {
        char s[40];
    } KAY;
    KAY k[10];
    void sirala(int *, int, struct kayit *);
    
    int main()
    {
        FILE *fp;
        fp = fopen("d.txt", "r");
        struct kayit {
            char s[40];
        };
        struct kayit k[10];
    
    The red bit is all duplicate.

    For example, reading the file might be
    Code:
    #include <stdio.h>
    #include <string.h>
    typedef struct kayit {
        char s[40];
        int  score;
    } KAY;
    
    void sirala(int *, int, struct kayit *);
    
    int main()
    {
        char buff[BUFSIZ];
        FILE *fp;
        KAY k[10];
        int i = 0;
    
        fp = fopen("d.txt", "r");
        while ( i < 10 && fgets(buff, sizeof buff, fp) != NULL) {
            if ( sscanf( buff, "&#37;s %d", k[i].s, &k[i].score ) == 2 ) {
                i++;
            }
        }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  7. #7
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    The problem is when I erase the duplicate part :
    this is like
    Elisha 60
    Roberto 70Alex 90

    Why alex become adjacent to Roberto?

    -------------

    Also Salem , I tried what you told before I posted here . I couldnt read the int form the string if string included a letter or anything different from number .That is why I placed a strpbrk function there. What may the problem be?

  8. #8
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    For example :

    Code:
    #include <stdio.h>
    #include <string.h>
    int main()
    {
    
    	char s[20]=" a 4 naber";
    	 int i;
    	sscanf(s,"%d",&i);
    printf("%d",i);
    
    	return 0;
    }
    It returns like 260948273..

  9. #9
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    Hope this helps you....

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define MAX_SIZE 128
    
    typedef struct _Person
    {
            int grade;
            char *name;
    }Person;
    
    //Functions.
    
    Person *GetRecordsFromFile(char *filename, int *Counted)
    {
           if(!filename)
           {
                        printf("Wrong Filename, enter a valid one.\n");
                        return NULL;
           }
           else
           {
               FILE *f = fopen(filename, "r");
               if(!f)
               {
                     printf("Can not open file %s\n", filename);
                     return NULL;
               }
               else
               {
                   char *buffer = (char *)calloc(MAX_SIZE, sizeof(char));
                   if(!buffer)
                   {
                              printf("Memory Error.\n");
                              return NULL;
                   }
                   else
                   {
                       int i = 0;
                       int j = 0;
                       int index = 0;
                       char *pointer = NULL;
                       char *p = NULL;
                       Person *per = (Person *)calloc(1,  sizeof(Person));
                       if(per == NULL)
                              return NULL;
                       else
                       {
                           while(fgets(buffer, MAX_SIZE, f) != NULL)
                           {
                                           if(buffer[strlen(buffer) - 1] == '\n')
                                                                    buffer[strlen(buffer) - 1] = '\0';
                                           //Have the buffer, parse the data.
                                           
                                           pointer = strchr(buffer, ' ');
                                           if(pointer == NULL)
                                           {
                                                      printf("Wrong format in %s\n", filename);
                                                      break;
                                           }
                                           else
                                           {
                                               index = pointer - buffer;
                                               index = index < 0 ? -index : index;
                                               per[i].name = (char *)calloc(index + 1, sizeof(char));
                                               if(per[i].name)
                                               {
                                                              for(p = buffer; *p != ' '; p++)
                                                                    per[i].name[j++] = *p;
                                                              per[i].name[j] = '\0';
                                               
                                                              if(sscanf(pointer, "%d", &per[i].grade) != 1)
                                                              {
                                                                  printf("Could not get the grade.\n");
                                                                  break;
                                                              }
                                               
                                                              per = (Person *)realloc(per, sizeof(Person));
                                                              i++;
                                                              j = 0;
                                               }
                                               else
                                               {
                                                   printf("Memory Error.\n");
                                                   break;
                                               }
                                           }
                           }
                           if(feof(f))
                           {
                                      //Return how many persons read.
                                      *Counted = i;
                           
                                      //Free buffers.
                                      free(buffer);
                           
                                      //Close file.
                                      fclose(f);
                           
                                      //Return struct.
                                      return per;
                           }
                           else
                           {
                               printf("Earlier exit, not all records are read from file %s\n", filename);
                               return NULL;
                           }
                       }
                   }
               }
           }
    }
    
    //Sort the records according to grade.
    //Use of bubble sort here.
    
    void SortPersons(Person *pers , int N)
    {
         if(pers)
         {
                 int i = 0;
                 int swapped = 0;
                 Person per;
                 memset(&per, 0, sizeof(Person));
                 do
                 {
                              swapped  = 0;
                              for(i = 0; i < N - 2; i++)
                              {
                                    if(pers[i].grade > pers[i + 1].grade)
                                    {
                                                     memcpy(&per, &pers[i], sizeof(Person));
                                                     memcpy(&pers[i], &pers[i+1], sizeof(Person));
                                                     memcpy(&pers[i+1], &per, sizeof(Person));
                                                     
                                                     swapped = 1;
                                    }
                              }
                 }while(swapped);
         }
    }
                                                                                                                                                                                                                                                   
    int main(int argc, char *argv[]) 
    {
        int i;
        int n = 0;
        Person *persons = GetRecordsFromFile("test.txt", &n);
        for(i = 0; i < n; i++)
              printf("Person[%d] has name %s and grade %d\n", i, persons[i].name, persons[i].grade);
        printf("\n\n\n"); 
        SortPersons(persons, n);
        for(i = 0; i < n; i++)
              printf("Person[%d] has name %s and grade %d\n", i, persons[i].name, persons[i].grade);
        printf("Hit any key to continue...\n");
        getch();
      return 0;
    }
    Printed Results.

    Person[0] has name nikos and grade 23
    Person[1] has name kostas and grade 11
    Person[2] has name baggelis and grade 33
    Person[3] has name giannis and grade 99
    Person[4] has name kadmos and grade 13
    Person[5] has name ilias and grade 45
    Person[6] has name gionis and grade 67



    Person[0] has name kostas and grade 11
    Person[1] has name kadmos and grade 13
    Person[2] has name nikos and grade 23
    Person[3] has name baggelis and grade 33
    Person[4] has name ilias and grade 45
    Person[5] has name giannis and grade 99
    Person[6] has name gionis and grade 67
    Hit any key to continue...

    //The names are in Greek but it does not matter, create a file and give your names.


  10. #10
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    I will have a look at it thank you for your effort.

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    @Bokarinho
    We try to help people by explaining where they went wrong, so they can learn for themselves. Simply handing over a complete answer is not the way.

    > It returns like 260948273..
    You didn't look at the return result of sscanf to find out whether it worked or not. In this case, it tried to match "&#37;d" against the letter "a", and failed at that point, leaving your value uninitialised.

    > That is why I placed a strpbrk function there. What may the problem be?
    I think my code makes the need to call strpbrk() redundant.

    > memcpy(&per, &pers[i], sizeof(Person));
    Did you know that structs can be assigned?
    As in
    Code:
    per = pers[i];
    pers[i] = pers[i+1];
    pers[i+1] = per;
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    Dude , why do you do this complicated codes for such a simple thing? Also cant you assign struct variables to other struct variables from the same struct?
    Last edited by ozumsafa; 07-24-2007 at 05:50 AM.

  13. #13
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    Salem the last point you have made , it is not about me is it ? Also , thanks for your beneficial response , also thanks to the bokarinho , but I dont think I need such lots of codes for this simple program..

  14. #14
    Registered User
    Join Date
    Jul 2007
    Posts
    151
    Doesnt it control sscanf ? :

    Code:
    for(y=0;y<=x;y++) {
    			if(sscanf(k[i].s,"&#37;d",&c[i])==1) break;
    		}
    dont bother with y and x. I am just trying to reach integer of the line. It doesn work . What Do I do wrong?

  15. #15
    Registered User
    Join Date
    Jun 2007
    Posts
    63
    @Salem: Are you sure that you can do that with structs?if it is possible i didnt know that i will use it.
    @ozumsafa: The above code was not so much complicated nor too much, was rather simple. I can not understand you. You may wite it using less lines but the whole way will be the same.

    @Salem: I think you are right, i will try to help not to give the whole answer.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. File transfer- the file sometimes not full transferred
    By shu_fei86 in forum C# Programming
    Replies: 13
    Last Post: 03-13-2009, 12:44 PM
  2. SYnchronize read & write of a cache file
    By lei_michelle in forum C Programming
    Replies: 4
    Last Post: 02-26-2008, 05:49 PM
  3. write and read system calls
    By nacho4d in forum C Programming
    Replies: 4
    Last Post: 01-28-2008, 10:59 AM
  4. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  5. Can I write & read file in same program?
    By chad03 in forum C Programming
    Replies: 2
    Last Post: 08-04-2003, 08:39 AM