I am trying to write the string to text file after heap sort....
it works correctly, just don't know why there's some weird charracter in the output file.. Any help with be appreciated.

Content of input file in1 is abc

#include <stdio.h>
#include <ctype.h>
#include <string.h>
using namespace std; 
#define DISPLAY 80
#define PAGE_LENGTH 20
void fnSortHeap(char array[], int arr_ubound);
int main(int argc, char *argv[])
   char filename[80]="in1.dat";
   FILE *pfile;
  char buffer[80];
   int count = 0;
   int lines = 0;
   int i = 0;

   if((pfile = fopen(filename, "rb")) == NULL){
       printf("Sorry, can't open %s", filename);
       return -1;

    // while((count < sizeof buffer)) /* If the buffer is not full  */
      for( i = 0 ; i< sizeof buffer;i++)
          buffer[i]= (char)fgetc(pfile);
              printf("%c", buffer[i]);
              //if(buffer[i] == "\n")
                //        break;
    for( i = sizeof buffer;i>1;i--)
  printf("\n sorted array\n\n");   
 for( i =0 ; i <sizeof buffer; i++) 
 printf("%c ",buffer[i] );
   FILE *p = NULL;
  char *file = "Hello.txt";
  //char buffer[80] = "abcghihijjklmnopuvw";
  size_t len = 0;
  p = fopen(file, "w");
  if (p== NULL) {
  printf("Error in opening a file..", file);
  len = sizeof buffer ;
  fwrite(buffer, 1, 80, p);
  printf("\nWritten Successfuly in the file.\n");

 printf("\nBelow is what inside the buffer\n");
 for( i =0 ; i <sizeof buffer; i++) 
 printf("%c ",buffer[i] ); 
 printf("\nabove is what inside the buffer\n");
void fnSortHeap(char array[], int arr_ubound){
  int i, o;
  int lChild, rChild, mChild, root, temp;
  root = (arr_ubound-1)/2;

  for(o = root; o >= 0; o--){
  lChild = (2*i)+1;
  rChild = (2*i)+2;
  if((lChild <= arr_ubound) && (rChild <= arr_ubound)){
  if(array[rChild] >= array[lChild])
  mChild = rChild;
  mChild = lChild;
  if(rChild > arr_ubound)
  mChild = lChild;
  mChild = rChild;

  if(array[i] < array[mChild]){
  temp = array[i];
  array[i] = array[mChild];
  array[mChild] = temp;
  temp = array[0];
  array[0] = array[arr_ubound];
  array[arr_ubound] = temp;

There is no memset() on the buffer before you do anything with it, anything could be in there and when you heap sort the buffer there are probably some values in there which are getting sorted along with the 'good' data. Add a memset() right after the variable definitions and see what happens.

If the file was 80 bytes long then you wouldn't see the problem, but if it's only a few then it's highly likely that there will be some data floating around in memory which buffer[] has just taken.

This article has been dead for over six months. Start a new discussion instead.