Bubble sorting a file in C

991 views Asked by At

I wrote a program that connects to a server and recieves lines of code from it and then prints all the code lines to a text file, the thing is, that the server sends all the code lines not in order, what I mean is that in the text file that contains the code lines there is not order, it can be line 55 and after it line 33, I am trying to write a function that will sort the file so the code lines will be in order, I know I need to use bubble sort and do a casting of the line numbers which are in string to int, but I have never tried bubble sorting a text file before, here is my code:(ignore the notes)

#define  _WINSOCK_DEPRECATED_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<winsock2.h>
#include<windows.h>
#include<string.h>


#define LEN 1024

void sortcode(FILE *fp);
int main(void)
{
    FILE *fp;
    fp = fopen("theCode.txt", "wt");
    int i;
    WSADATA info;
    char str[LEN];
    str[LEN - 1] = NULL;
    char str2[LEN];
    str2[LEN - 1] = NULL;
    char temp[8] = "5000000"; // the row number
    int j = strlen(temp) - 1;// the index of the temp string
    int k = 0;
    int err;
    err = WSAStartup(MAKEWORD(2, 0), &info);
    if (err != 0)
    {
        printf("WSAStartup failed with error: %d\n", err);
        exit(1);
    }
    int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s == INVALID_SOCKET)
    {
        printf("Error creating socket = %d\n", WSAGetLastError());
    }
    else
    {
        printf("Socket function succeeded\n");
    }
    struct sockaddr_in clientService;
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr("54.152.161.133");
    clientService.sin_port = htons(6714);
    int cResult = connect(s, (struct socketaddr*)&clientService, sizeof(clientService));
    if (cResult == SOCKET_ERROR)
    {
        printf("Connect function failed with error: %d\n", WSAGetLastError());
        cResult = closesocket(cResult);
        if (cResult == SOCKET_ERROR)
        {
            printf("Close socket function closed with an error: %1d\n", WSAGetLastError());
        }
        WSACleanup();
        //return 1;
    }
    //Until this part, it's all taken from the slideshow.
    send(s, "100", LEN, 0); //Sending code 100: Requesting to connect.
    printf("Request to connect was sent using 100\n");
    recv(s, str, LEN, 0); //Recieving a code to the string str.
    printf("Code recieved: %s\n", str);
    if (strcmp("101", str) == 0)
    {
        printf("Connection was successful\n");
    }
    else
    {
        printf("The connection failed\n");
    }
    send(s, "400", LEN, 0); //Sending a request for the number of code lines.
    printf("Request for the amount of code lines was sent using 400\n");
    recv(s, str, LEN, 0); //Recieving the answer on str, you'll get code 401+The number of lines for example 4010079.
    printf("String recieved: %s\n", str);
    printf("The amount of code lines: 0079\n");
    printf("%s", str);
    for (k = 1; k <= 7; k++)
    {
        for (i = 0; i <= 9; i++)
        {
            temp[j] = i + 0x30;
            send(s, temp, LEN, 0);
            recv(s, str, LEN, 0);
            fprintf(fp, str);
            fprintf(fp, "\n");
        }
        temp[j - 1] = k + 0x30;
        temp[j] = 0 + 0x30;
    }
    //You need to add the part with the files where you print all the lines including the code in them to a txt file.
    //Good Luck, first try to solve that i to string conversion.
    system("PAUSE");
    return (0);
}
void sortcode(FILE *fp)
{
    int i, j, k;
    char str2[LEN];
    fp = fopen("theCode.c", "rt");
    for (i = 0; i < 79; i++)
    {
        for (j = 3; j < 7; j++)
        {

        }
    }
}
2

There are 2 answers

2
John Bollinger On

Even if you are determined to write your own sort function instead of using qsort(), the bubble sort algorithm is a pretty bad choice for more than a bare handful of items.

If you're willing to buffer all the lines in memory until you've read and sorted all of them, as is probably your best bet, then you should consider sorting them as you go. Each time you read a new line, find its place among those already read, and insert it there. This is essentially an insertion sort.

If you expect your lines to be mostly in order, then search linearly for each insertion point, from back to front. This is the standard insertion sort, and it does extremely well for inputs that are approximately in order. For large numbers of lines in no particular order, you could consider instead using a binary search to find each insertion point.

If you use a linked list to hold the lines (a reasonable choice if you don't know in advance how many there will be), then the binary-search alternative scales well to large inputs.

6
Man Vs Code On

You could read the entire file into an array of lines. Then you could use qsort() in stdlib.h to sort your array.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static int compare_lines( const void* left, const void* right )
{
    const char* l = *((char**)left);
    const char* r = *((char**)right);
    return strcmp( l, r );
}

int main(int argc, char* argv[])
{
    char** lines           = NULL;
    size_t number_of_lines = 0;

    const char* fruits[] = {
        "Banana",
        "Orange",
        "Ugli Fruit",
        "Pomegranate",
        "Peach",
        "Apple",
        "Blueberry",
        "Raspberry",
        "Guava",
        "Cherry",
        "Star Fruit",
        "Pomelo",
        "Kiwi",
        "Pineapple",
        "Fig",
        "Papaya"
    };

    size_t len = sizeof(fruits) / sizeof(fruits[0]);

    for( size_t i = 0; i < len; i++ )
    {
        void* p = realloc( lines, (number_of_lines + 1) * sizeof(char*) );
        if( p ) lines = p;
        else goto done;

        lines[ number_of_lines ] = malloc( strlen(fruits[ i ]) + 1 );
        strcpy( lines[ number_of_lines ], fruits[ i ] );
        number_of_lines++;
    }

    qsort( lines, number_of_lines, sizeof(char*), compare_lines );


    for( size_t i = 0; i < number_of_lines; i++ )
    {
        printf( "%zu.) %s\n", i, lines[ i ] );
    }

done:
    if( number_of_lines > 0 && lines )
    {
        for( size_t i = 0; i < number_of_lines; i++ ) free( lines[ i ] );
        free( lines );
    }
    return 0;
}

EDIT: Fixed pointer bug in compare_lines().