Thread: sorting data from file input

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    10

    sorting data from file input

    I am a newbie to C and I was wondering if someone has a small piece of code I could use to sort the following file input. I have made a small file with 11 social security numbers and I need these to be sorted in descending order and then displayed on the screen. Right now the data is displayed without sorting. Any help would be appreciated. Thanks.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main(void)
    {
    	int x, y[10];
    	FILE *fp;
    	fp = fopen("testdat.txt","r");
    	for (x=0;x<10;x=x++)
    	{
    		fscanf(fp,"%d",&y[x]);
    		printf("%d\n",y[x]);
    	}
    	fclose(fp);
    }

  2. #2
    .
    Join Date
    Nov 2003
    Posts
    307
    use the OS to sort, don't write a bubble sort.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main(void)
    {
    	int x, y[10];
    	FILE *fp;
    	/* this is a windows box */
    	shell("sort testdat.txt /o tmp.tmp");
    	/* if this is a unix box
    	shell("sort testdat.txt -o tmp.tmp");
    	fp = fopen("tmp.tmp","r");
    	for (x=0;x<10;x=x++)
    	{
    		fscanf(fp,"%d",&y[x]);
    		printf("%d\n",y[x]);
    	}
    	fclose(fp);
    }
    this may not be what your teacher would want, though

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,666
    > for (x=0;x<10;x=x++)
    x=x++ is undefined, just do
    for (x=0;x<10;x++)

    As for sorting, the quick and dirty bubble sort is probably OK for such a small array.

    Search the board for previous examples
    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.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how do you input data from a file into an array?
    By jorgejags in forum C Programming
    Replies: 5
    Last Post: 11-03-2008, 02:48 PM
  2. C++ std routines
    By siavoshkc in forum C++ Programming
    Replies: 33
    Last Post: 07-28-2006, 12:13 AM
  3. HUGE fps jump
    By DavidP in forum Game Programming
    Replies: 23
    Last Post: 07-01-2004, 10:36 AM
  4. reading a columns input data file
    By vk13wp in forum C Programming
    Replies: 6
    Last Post: 04-28-2003, 01:32 PM
  5. simulate Grep command in Unix using C
    By laxmi in forum C Programming
    Replies: 6
    Last Post: 05-10-2002, 04:10 PM