0

could I get any hint about my code ? All i get is empty black screen.

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

#define MAX 20
int main()
{
int num,c, i, j, temp, array[20];

FILE *fp;
fp = fopen("input.txt", "r");  //Opening a file
if (fp == NULL)
{
    printf("File empty! \n");
    return 1;
}

while(i < MAX)
{
    fgets(fp, "%d", &array[i]);
    printf("\nARRAY %d",array[i]);
    i++;
}
fclose(fp);
*
*
*more code will be added

return 0;
}

Input.txt contains: 0005 0006 FFFF 0007 0003 FFFF 0004 0002 0001 FFFF 0000

Also, when the input.txt is empty, does not give error. I am trying to add these numbers from input into array[i] so how could sort them. Any hint/help will help. Thank you.

6
  • 2
    while(i < MAX) -- What's the value of i? Commented Mar 20, 2016 at 12:36
  • 2
    Ask yourself what value i has when you do: while(i < MAX) ? If your answer is "I have no idea", you're in good company, because neither does the program. i is uninitialized. Even evaluating it invokes undefined behavior. And the order of your parameters in your fgets invoke are wrong: fp should be the last parameter; not the first. And fgets expects a char buffer, not an int buffer, so I suspect you meant to use fscanf. I can't fathom how your compiler didn't at-least warn you about these. Commented Mar 20, 2016 at 12:36
  • for ease of readability and understanding by us humans: 1) indent after every opening brace '{'. unindent before every closing brace '}'. 2) following the axiom: only one statement per line and (at most) one variable declaration per statement. Commented Mar 21, 2016 at 15:21
  • this statement: printf("File empty! \n"); has a few problems. 1) route error messages to stderr, not stdout. 2) "file empty" is not the current state, the problem is the call to fopen() failed, and the OS knows why. Use: perror( "fopen to read input.txt failed" ); Commented Mar 21, 2016 at 15:29
  • before trying to 'run' that code you need to get a clean compile. Always enable all the warnings when compiling, then fix those warnings. == using gcc -Wall -Wextra -pedantic -Wconversion -std=gnu99 -c myfile.c -o myfile.o the compiler outputs 10 warnings, several of which are critical,, Commented Mar 21, 2016 at 15:50

1 Answer 1

1

Among the things wrong in your code:

  • i is uninitialized. Evaluating uninitialized data invokes undefined behavior, the root of most evil in C programs (and pretty much anywhere else). Severity: critical.
  • The call to fgets is not correct. The parameter list you're providing suggests you should be using fscanf. Severity: Fatal (will not compile).
  • The format flag for reading hexadecimal data is wrong. It should be %X. Severity: Medium-High, your code will stop reading as soon as the first FFFF is encountered, thus giving you inaccurate results.
  • The reading operation should be checked for success. Severity: Medium-High. You should stop reading once no more values can be scanned in.

There are other things that, though not critical, are advised. Your sizing counter is int, but is supposed to represent a magnitude of objects. Thus it should be an unsigned type. The standard library provides a type it uses for such operations, size_t, and I advise you use it here.

All of the above rectified in the following, which includes a braindead-simple bubble-sort to perform your actual sorting operation (the algorithm of which is available in roughly a million places on the web).

Code

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

#define MAX 20

void bubblesort(int ar[], size_t count);

int main()
{
    int array[MAX];
    size_t count=0;

    // open input file
    FILE *fp = fopen("input.txt", "r");  //Opening a file
    if (fp == NULL)
    {
        printf("File empty! \n");
        return EXIT_FAILURE;
    }

    // read all integers from the file
    for (count=0; count<MAX && fscanf(fp, "%X", array+count) == 1; ++count)
        printf("%04X ", array[count]);
    putc('\n', stdout);

    // close file, no longer needed
    fclose(fp);

    // sort the integers
    bubblesort(array, count);

    for (size_t j=0; j<count; ++j)
        printf("%04X ", array[j]);
    putc('\n', stdout);

    return EXIT_SUCCESS;
}

// simple bubblesort
void bubblesort(int ar[], size_t count)
{
    int swapped = 1;
    while (count-- && swapped)
    {
        swapped = 0; // reset swap flag
        for (int i=0; i<count; ++i)
        {
            if (ar[i] > ar[i+1])
            {
                int tmp = ar[i];
                ar[i] = ar[i+1];
                ar[i+1] = tmp;
                swapped = 1; // swapped; set flag
            }
        }
    }
}

Input (from input.txt)

0005 0006 FFFF 0007 0003 FFFF 0004 0002 0001 FFFF 0000 

Output

0005 0006 FFFF 0007 0003 FFFF 0004 0002 0001 FFFF 0000 
0000 0001 0002 0003 0004 0005 0006 0007 FFFF FFFF FFFF 

Best of luck.

Sign up to request clarification or add additional context in comments.

2 Comments

I should use Insertion Sort instead of bubble sort. Do I need that line "void bubblesort(int ar[], size_t count);" or can i replace "bubblesort with InsertionSort ?
Use whatever sort you want. That is as simple as they come. If you want a NlogN sorting algorithm the standard library provides one already with qsort. The only reason I used a bubblesort is because (a) its brain-dead simple to implement (obviously), (b) it is insanely cache friendly for tiny lists like this, and (c) does not use the overhead of the void* data abstraction of qsort. If this were more than a hundred or so items, I'd probably have insertion-sorted, and for something over a thousand or so, probably merge-sorted or qsorted.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.