Thread: Sorting numbers in a file

  1. #1
    Registered User
    Join Date
    Feb 2004
    Posts
    73

    Sorting numbers in a file

    The title is misleading in that the numbers in the file are displayed in a column.

    Example:

    3
    5
    10
    4
    8
    1
    2
    etc...

    The resulting file also has to be in that formatting, so:

    1
    2
    3
    4
    5
    6

    The problem I am having right now is getting the numbers read from the file and into an array. The problem is that I have it reading character by character so if it is a two digit number, say 10, it will put 1 into one element and 0 into another one. That is one problem I know about. The other major one is how I can print the array, once it is sorted, back into another file with that above formatting. Here is what I have working right now.....

    Code:
    void quicksort(int *array, int size)     //sorting function for the array
    {
       int a,b,temp;
    
       for(a=0;a<(size-1);a++){
         for(b=a=1;b<size;b++){
           if(array[a] > array [b]){
             temp=array[b];
             array[b] = array[a];
             array[a] = temp;
           }
         }
       }
    }
    
    int main(int argc, char *argv[])
    {
    
    FILE *quick, *fp;
    char c;
    int n;
    int array[101];
    
        fp=fopen(argv[1], "r");
        quick=fopen("sorted", "w");
    
        while((c=fgetc(fp)) != EOF){   //gets the numbers, put them into an array
          for(n=0; n <101; n++){
            if(c != '\n'){
              array[n] = c;
            }
          }
        }
    
        quicksort(array, 101);        //sort the numbers
    
        while(array != NULL){      //Puts the numbers back into a new file
          for(n=0; n <101; n++){
              fputc(array[n],quick);
          }
        }
    
    
    fclose(quick);
    
          system("PAUSE");
          return 0;
    }

  2. #2
    Obsessed with C chrismiceli's Avatar
    Join Date
    Jan 2003
    Posts
    501
    here is what you are going to have to do to get the multiple digit numbers into one index of the array:
    1. Use fgetc() and see if it is a \n, if not, you have to keep calling it to get the whole number while putting the char you got into an array. Then you have to convert the string you made by using fgetc() over and over into a number, you could strtol() for this.

    After all of that, you sort, bubble or whatever you want, then use sprintf() to put the to a file.
    Help populate a c/c++ help irc channel
    server: irc://irc.efnet.net
    channel: #c

  3. #3
    'AlHamdulillah
    Join Date
    Feb 2003
    Posts
    790
    what you are looking for(since I assume you dont want to use fscanf), is look for when the current character is '\n', and on all of the characters previous to that on the line just read them into the same array element by reading a digit, multiplying by ten and adding another digit, and so on.

  4. #4
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    See, I know what I have to do in those terms guys, but I am completely lost as to how to do them. I dont know how to get fgetc() to keep reading until \n and put everything it read up until that point into one array element then increment down to the next line and the next array element.

  5. #5
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    555
    you could just use fgets and atoi instead, if your file has the requirement of only containing numbers, one on each line.

    Code:
    char buf[11]
    int i;
    
    for (i=0 ;fgets(fp,buf,sizeof(buf)) && i < 101; i++ )
      array[i]=atoi(buf);

  6. #6
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    555
    Quote Originally Posted by pxleyes
    See, I know what I have to do in those terms guys, but I am completely lost as to how to do them. I dont know how to get fgetc() to keep reading until \n and put everything it read up until that point into one array element then increment down to the next line and the next array element.
    Its quite simple:
    Code:
    int c;
    
    while ((c=fgetc(fp)) != '\n')
      array[i] = (c-'0') + array[i]*10;
    of course for this to work you would have to initialize the array to all zeros.

    but its really just making it more complicated doing it that way, then just using fgets.

    *EDIT* left out the conversion of c to a int, heh. actually C should be int already. but it still doesnt hold the proper value we want.
    Last edited by nonpuz; 04-13-2004 at 01:00 PM.

  7. #7
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    why are you *10. I dont get that part.

  8. #8
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    Also, what in the world is atoi. I have never encountered that before.

  9. #9
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    555
    It works like this, say you have in your file:

    1023

    fgetc reads in the first 1, and goes through the evaluation array[i] = 1 + array[i]*10; array[i] is zero right now, so this is actually array[i] = 1 + 0*10 == 1. next it reads in the 0, so array[i] = 0 + 1*10 = 10. next it reads in the 2, array[i] = 2 + 10*10 = 102.
    You understand? if you read in each character you have to manipulate the number, its not like a string where you can just add on to the end its one int, not an array of int that you're working with. Yes you are working with an array of int, but each iteration deals with only one element of the array.

  10. #10
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    oooo, ok. That makes sense.


    I am wondering if that will work when I dont know the number of numbers in the file because the size of the array then depends on the number of numbers, and if you initialize it all to 0, it will sort it and print it out weird.

  11. #11
    Ultraviolence Connoisseur
    Join Date
    Mar 2004
    Posts
    555
    Quote Originally Posted by pxleyes
    Also, what in the world is atoi. I have never encountered that before.
    atoi takes a string and returns the integer that is in the string, up until it encounters a non-integer.

  12. #12
    'AlHamdulillah
    Join Date
    Feb 2003
    Posts
    790
    am wondering if that will work when I dont know the number of numbers in the file because the size of the array then depends on the number of numbers, and if you initialize it all to 0, it will sort it and print it out weird.
    include a sentinel value, a value which must never happen, so that when you print out the list it will skip elements that contain that value.

  13. #13
    Registered User
    Join Date
    Dec 2001
    Posts
    34
    This example should get you close to what you want. More error checking could be added.

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    #define MAX_ARRAY_INTS  101
    #define MAX_LINE_LENGTH 100
    
    void quicksort(int a[], int left, int right);
    
    int main(int argc, char *argv[])
    {
    	FILE *quick, *fp;
    	char s[11];
    	int n;
    	int x;
    	int array[MAX_ARRAY_INTS];
    
    	if ((fp=fopen(argv[1], "r")) == NULL)
    		exit(-1);
    
    	if ((quick=fopen("sorted.txt", "w")) == NULL)
    	{
    		fclose(fp);
    		exit(-2);
    	}
    
    	n=0;
    	/* in this case, fgets will read up to 100 characters */
    	/* per line including the newline character */
    	while((fgets(s,MAX_LINE_LENGTH,fp)) != NULL)
    	{
    		/* overwrite the '\n' with a null character */
    		s[strlen(s)-1] = '\0';
    		/* copy the number (changing the string into an integer) into the array */
    		array[n++] = atoi(s);
    	}
    	fclose(fp);
    
    	/* do the quicksort */
    	quicksort(array, 0, n-1) ;
    
    	/* save the integers back to the file */
    	for(x=0; x < n; x++)
    	{
    		fprintf(quick,"%d\n",array[x]);
    	}
    	fclose(quick);
    
    	system("PAUSE");
    	return 0;
    }
    
    
    /* helper function for quicksort */
    int partition( int a[], int l, int r) 
    {
    	int pivot, i, j, t;
    	pivot = a[l];
    	i = l; j = r+1;
    
    	while( 1)
    	{
    		do ++i; while( a[i] <= pivot && i <= r );
    		do --j; while( a[j] > pivot );
    		if( i >= j ) break;
    			t = a[i]; a[i] = a[j]; a[j] = t;
    	}
    	t = a[l]; a[l] = a[j]; a[j] = t;
    	return j;
    }
    
    /* one of the many quicksorts available on the web */
    void quicksort( int a[], int l, int r)
    {
    	int j;
    
    	if( l < r ) 
    	{
    		// divide and conquer
    		j = partition( a, l, r);
    		quicksort( a, l, j-1);
    		quicksort( a, j+1, r);
    	}
    }

  14. #14
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    After looking up the stoi function, I like that a lot. I am trying to implement it, but I am getting a lot of warning. Take a look at what I hope is close to my final version.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    void quicksort(int *array, int size)     //sorting function for the array
    {
       int a,b,temp;
    
       for(a=0;a<(size-1);a++){
         for(b=a=1;b<size;b++){
           if(array[a] > array [b]){
             temp=array[b];
             array[b] = array[a];
             array[a] = temp;
           }
         }
       }
    }
    
    int main(int argc, char *argv[])
    {
    
    FILE *quick, *fp;
    char c, buf[11];
    int n, i, s=101;
    int array[101];
    
        fp=fopen(argv[1], "r");
        quick=fopen("sorted", "w");
    
    for (i=0; fgets(buf,sizeof(buf),fp) && i < 101; i++){
      array[i]=atoi(buf);
    }
    
    quicksort(array, s);        //sort the numbers
    
        while(array != NULL){      //Puts the numbers back into a new file
          for(n=0; n <101; n++){
              fprintf(quick, "%d\n", array[n]);
          }
        }
    
    
    fclose(quick);
    
          system("PAUSE");
          return 0;
    }
    Last edited by pxleyes; 04-13-2004 at 02:05 PM.

  15. #15
    Registered User
    Join Date
    Feb 2004
    Posts
    73
    Yea, no matter what I try, I cant get those numbers to go into an array right. Any help one those few lines would be nice.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. opening empty file causes access violation
    By trevordunstan in forum C Programming
    Replies: 10
    Last Post: 10-21-2008, 11:19 PM
  3. Post...
    By maxorator in forum C++ Programming
    Replies: 12
    Last Post: 10-11-2005, 08:39 AM
  4. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  5. Unknown Memory Leak in Init() Function
    By CodeHacker in forum Windows Programming
    Replies: 3
    Last Post: 07-09-2004, 09:54 AM