Thread: Newbieish Question: About a buffer for Sorting a Text file.

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    24

    Smile Newbieish Question: About a buffer for Sorting a Text file.

    Hi im realtively new to c, I am trying to write a program that will read
    in a text file and sort it, and then write the result back over the the text file.

    So far im having trouble reading the file into a buffer. Now i was thinking i'd just read it into a 2d char Array. So to actually make the buffer i need the number of lines in the textfile which i wrote a method to get, but what has stumped me is how to actually create the buffer if its allready initalized. Plus im also thinking there is a much better way to do this then my approach.

    Here is my code so far
    Code:
    #include <stdio.h>
    #include <string.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    /***************************************
    This program shall SORT!
    Made by Mark Crick
    ©2005 Mark Crick
    ****************************************/
    #define MAX 256
    
    int readfileintoarray(char fileName[]);
    int sizeoffile(char fileName[]);
    
    main(int argc, char *argv[])
    {
    	int linesoftxtinfile = 0; //Eventually will contain the number of lines in the txt file.
    	int i = 0; // a iterator
    //	char *fileBuffer[][]; //The planed buffer but need to be commented out for complie to work
    	if(argc == 2)
    	{
    		i = numberoflinesinfile(argv[1]);
    		printf("Sort:Size of array:  %i \n",i);
    	}
    	else
    	{
    		printf("Sort: Incorrect argument \n Syntax: Sort [file to sort]");
    		return(1);
    	}
    	printf("Sort.exe Made by Mark Crick ©2005 Mark Crick \n");
    	return(0);
    }
    int writefilefromarray(char fileName[])// This will write from buffer to the file
    {
      	FILE *filePtr;
      	char *textLine[MAX];
      	if((filePtr = fopen(fileName,"w")) != 0)
    	{
    		  while(feof(filePtr) == 0)
    		  {
    			if(fgets(textLine, MAX, filePtr) != NULL)
    			{
    				// fprintf(writePtr,"%s",textLine); //write line from Buffer.
    			}
    
    		  }
    		fclose(filePtr);
    	}
    	else
    	{
    		printf("Sort: Could not read filename :%s\n",fileName);
    		exit(1);
    	}
    }
    int readfileintoarray(char fileName[])// This will read the text file into the buffer array
    {
      	FILE *filePtr;
      	char *textLine[MAX];
      	if((filePtr = fopen(fileName,"r")) != 0)
    	{
    		  while(feof(filePtr) == 0)
    		  {
    			if(fgets(textLine, MAX, filePtr) != NULL)
    			{
    				//Put line in Buffer.
    			}
    
    		  }
    		fclose(filePtr);
    	}
    	else
    	{
    		printf("Sort: Could not read filename :%s\n",fileName);
    		exit(1);
    	}
    }
    int numberoflinesinfile(char fileName[])//Should return the number of lines in the textfile
    {
    	/*int rtnVal = -1;
    	struct stat statBuff;
    
    	if (fstat(fileName, &statBuff) == 0)
    	{
    		rtnVal = statBuff.st_size;
    	}*/
    
    	FILE *filePtr;
    	int i =0;
      	if((filePtr = fopen(fileName,"r")) != 0)
    	{
    		  while(feof(filePtr) == 0)
    		  {
    			if(fgets(textLine, MAX, filePtr) != NULL)
    			{
    				i++.
    			}
    
    		  }
    		fclose(filePtr);
    	}
    	else
    	{
    		printf("Sort: Could not read filename :%s\n",fileName);
    		exit(1);
    	}
    
    	return i;
    }
    void selectionSort ( int arr[], int size )
    {
       //Write sort later
    }
    
    // swap function for integers
    void swap ( int* x, int* y )
    {
       //Write sort later
    }

    thanks

  2. #2
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    One thing that stands out is:

    Code:
    char *textLine[MAX];
    should be
    Code:
    char textLine[MAX];
    also notice the highlighted period, won't compile

    Code:
    if(fgets(textLine, MAX, filePtr) != NULL)
    {
    	i++.
    }
    Finally, textLine has to be defined in the numberoflinesinfile function.

    Bob

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    24
    Ahh heh yeah whoops. Seeing as i dont use textLine in that loop (its just a count of the lines) i could just use a "" couldnt i?.

  4. #4
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    even with your code commented out, my compiler barfs.
    i'm not sure if this is homework or not, but are you not supposed to use fread and fwrite. Seems to me it would make your life simpler. I would look into those, if your not supposed to use them, then forgive me.

    As for setting aside a buffer. your code
    Code:
    char *fileBuffer[][];
    is a 2 demensional arry of char *. Maybe its just me, but i would simply allocate a buffer as in
    Code:
     char buffer[BUFSIZ]
    main also returns an int...but i'm sure someone else will berate you for that. I don't mean to be rude but i would read the chapter on files over before i have another go at this code.
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  5. #5
    Registered User
    Join Date
    Oct 2005
    Posts
    24
    Umm nah its not homework. Im just learning c at my spare time at work. Yeah ive been using online tutorials ,none of them mentioned fread() fwrite() well not for text files they dont...
    ill have a look into it thanks for the advice

  6. #6
    Registered User
    Join Date
    Oct 2005
    Posts
    24
    Oh and returning the int in the main. I started out with exit(1);, but for some reason my comipler would give a warning
    Warning W8004 H:\C exercises\sort.c 39: 'linesoftxtinfile' is assigned a value that is never used in function main.

    But when i return it doesnt. i think i saw someone do it somewhere on a online tut.

  7. #7
    Registered User
    Join Date
    Oct 2005
    Posts
    24
    Well i had another crack at it. this time got

    Code:
    #include <stdio.h>
    #include <string.h>
    
    /***************************************
    This program shall SORT!
    Made by Mark Crick
    ©2005 Mark Crick
    ****************************************/
    #define MAX 256
    
    void readfileintoarray(char fileName[],char filebuffer[]);
    void writefilefromarray(char fileName[],char fileBuffer[]);
    void swapchar ( char* x, char* y );
    void selectionsort ( char arr[], int size );
    
    main(int argc, char *argv[])
    {
     	char fileBuffer[BUFSIZ];
    	if(argc == 2)
    	{
    		readfileintoarray(argv[1],fileBuffer);
    		selectionsort(fileBuffer,sizeof(fileBuffer));
    		writefilefromarray(argv[1],fileBuffer);
    	}
    	else
    	{
    		printf("Sort: Incorrect argument \n Syntax: Sort [file to sort]");
    		exit(1);
    	}
    	printf("Sort.exe Made by Mark Crick ©2005 Mark Crick \n");
    	exit(0);
    }
    void writefilefromarray(char fileName[],char fileBuffer[])// This will write from buffer to the file
    {
      	FILE *filePtr;
    	if((filePtr = fopen(fileName,"w")) != 0)
    	{
    		fwrite(fileBuffer, sizeof(fileBuffer[0]), sizeof(fileBuffer)/sizeof(fileBuffer[0]), filePtr);
    		fclose(filePtr);
    	}
    	else
    	{
    		printf("Sort: Could not read filename :%s\n",fileName);
    		exit(1);
    	}
    }
    void readfileintoarray(char fileName[],char filebuffer[])// This will read the text file into the buffer array
    {
      	FILE *filePtr;
      	if((filePtr = fopen(fileName,"r")) != 0)
    	{
    		fread(filebuffer, sizeof(filebuffer[0]), sizeof(filebuffer)/sizeof(filebuffer[0]), filePtr);
    		fclose(filePtr);
    	}
    	else
    	{
    		printf("Sort: Could not read filename :%s\n",fileName);
    		exit(1);
    	}
    }
    void selectionsort (char arr[], int size )
    {
    	int indexOfMin, pass, j;
    	for ( pass = 0; pass < size - 1; pass++ )
    	{
    		indexOfMin = pass;
    
    		for ( j = pass + 1; j < size; j++ )
    		{
    			if(strcmp(arr[j],arr[pass]) < 0)
    			{
    				indexOfMin = j;
    			}
    		}
    		swapchar ( &arr[pass], &arr[indexOfMin] );
    	}
    
    }
    
    
    // swap function for char
    void swapchar ( char* x, char* y )
    {
       char temp;
       temp = *x;
       *x = *y;
       *y = temp;
    }
    only i get an error that has stumped me.

    Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
    H:\C exercises\sort.c:
    Warning W8065 H:\C exercises\sort.c 28: Call to function 'exit' with no prototype in function main
    Warning W8065 H:\C exercises\sort.c 31: Call to function 'exit' with no prototype in function main
    Warning W8070 H:\C exercises\sort.c 32: Function should return a value in function main
    Warning W8065 H:\C exercises\sort.c 44: Call to function 'exit' with no prototype in function writefilefromarray
    Warning W8065 H:\C exercises\sort.c 58: Call to function 'exit' with no prototype in function readfileintoarray
    Error E2342 H:\C exercises\sort.c 70: Type mismatch in parameter '__s1' (wanted 'const signed char *', got 'int') in function selectionsort
    Error E2342 H:\C exercises\sort.c 70: Type mismatch in parameter '__s2' (wanted 'const signed char *', got 'int') in function selectionsort
    *** 2 errors in Compile ***

    Tool completed with exit code 1



    Plus im pretty sure it wouldnt work anyway because arr[integer] would grab a char. But i thought i might try.
    Last edited by fatdunky; 10-27-2005 at 12:42 AM.

  8. #8
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    You need to #include <stdlib.h> for exit.

    The line 32 warning is that it is looking for main to return a value, because main returns an int. You've made main return int implicitly, which is a deprecated construct, you should declare main as "int main...".

    The line 70 error is because you're not passing strcmp two strings (char *).

  9. #9
    Registered User
    Join Date
    Oct 2005
    Posts
    24
    heh im back again. thanks for the help so far guys.

    Ive had another crack at it i seem to have most of it sorted out execpt for one thing. Swapping the strings in the array. I can't really figure out how to do it. (because they can be a diffrent size, and i figure that could screw up the array if i swapped them) anyone have any ideas. I was thinking of making an array of pointers to strings but have no idea of how to create it in the program from the way i read in the file.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    /***************************************
    This program shall SORT!
    Made by Mark Crick
    ©2005 Mark Crick
    ****************************************/
    #define MAX 256
    
    void readfileintoarray(char fileName[],char filebuffer[]);
    void writefilefromarray(char fileName[],char fileBuffer[]);
    void swapchar ( char* x, char* y );
    void selectionsort ( char arr[], int size );
    void splitString(char stringToSplit[],int startIndex, int endIndex, char string[], int size);
    void getstring(char arr[], int size, int pointer, char stringToGet[]);
    
    int main(int argc, char *argv[])
    {
     	char fileBuffer[BUFSIZ];
    	if(argc == 2)
    	{
    		readfileintoarray(argv[1],fileBuffer);
    		selectionsort(fileBuffer,sizeof(fileBuffer));
    		writefilefromarray(argv[1],fileBuffer);
    	}
    	else
    	{
    		printf("Sort: Incorrect argument \n Syntax: Sort [file to sort]");
    		exit(1);
    	}
    	printf("Sort.exe Made by Mark Crick ©2005 Mark Crick \n");
    	return(0);
    }
    void writefilefromarray(char fileName[],char fileBuffer[])// This will write from buffer to the file
    {
      	FILE *filePtr;
    	if((filePtr = fopen(fileName,"w")) != 0)
    	{
    		fwrite(fileBuffer, sizeof(fileBuffer[0]), sizeof(fileBuffer)/sizeof(fileBuffer[0]), filePtr);
    		fclose(filePtr);
    	}
    	else
    	{
    		printf("Sort: Could not read filename :%s\n",fileName);
    		exit(1);
    	}
    }
    void readfileintoarray(char fileName[],char filebuffer[])// This will read the text file into the buffer array
    {
      	FILE *filePtr;
      	if((filePtr = fopen(fileName,"r")) != 0)
    	{
    		fread(filebuffer, sizeof(filebuffer[0]), sizeof(filebuffer)/sizeof(filebuffer[0]), filePtr);
    		fclose(filePtr);
    	}
    	else
    	{
    		printf("Sort: Could not read filename :%s\n",fileName);
    		exit(1);
    	}
    }
    void selectionsort (char arr[], int size )
    {
    	int indexOfMin, pass, j;
    	char *stringj,*stringPass;
    	for ( pass = 0; pass < size - 1; pass++ )
    	{
    		indexOfMin = pass;
    
    		for ( j = pass + 1; j < size; j++ )
    		{
    			getstring(arr,size,j,stringj);
    			getstring(arr,size,pass,stringPass);
    			if(strcmp(stringj,stringPass) < 0)
    			{
    				indexOfMin = j;
    			}
    		}
    		swapchar ( &arr[pass], &arr[indexOfMin] );
    	}
    }
    void getstring(char arr[], int size, int pointer, char stringToGet[]) // will return -1 if nothing found
    {
    	int i;
    	for(i = pointer; i < size;i++)
    	{
    		if(arr[i] == '\n' || arr[i] == '\0' ||  arr[i] == '\r')
    		{
    			splitString(stringToGet,arr[pointer],arr[i],arr,size);
    			break;
    		}
    	}
    }
    // swap function for char
    void swapcharInArray()
    {
      
      
       
    }
    void splitString(char stringToSplit[],int startIndex, int endIndex, char string[], int size)
    {
    	int i;
    	for(i=0; i < size && i < endIndex; i++,startIndex++)
    	{
    		string[i] = stringToSplit[startIndex];
    	}
    }
    Last edited by fatdunky; 10-28-2005 at 12:01 AM.

  10. #10
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    First of all, you should eliminate all your syntax errors. The above code does not compile. For instance, you have to include stdlib.h for the exit function. And other quirks have to be addressed.

    Secondly, you've got quite a ways to go before the above code will perform your desired processing. It does need a lot of work. I would suggest you use a search sort algorithm such as a binary tree.

    It's your choice, fix the above code to properly sort a file which is doable but will be painful. Or, IMHO, use a simple elegant approach such as a binary tree.

    Good luck

    Bob

  11. #11
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    once again. #include <stdlib.h> for exit. don't implicityly declare it.
    Code:
    int main(int argc, char *argv[])
    {
     	char fileBuffer[BUFSIZ];
    	if(argc == 2)
    	{
    		readfileintoarray(argv[1],fileBuffer);
    		selectionsort(fileBuffer,sizeof(fileBuffer));
    in this case sizeof file buffer is 512 bytes which == 512 characters
    but you should specify that it is an int. so put BUFSIZ instead


    Code:
    void readfileintoarray(char fileName[],char filebuffer[])// This will 
    read the text file into the buffer array
    {
      	FILE *filePtr;
    
      	if((filePtr = fopen(fileName,"r")) != 0)
    fopen returns a FILE * on success and NULL if not. Use the predefined macro as the std has specified or if not then at least:
    Code:
    if((filePtr=fopen(filename,"r")))

    Code:
    		fread(filebuffer, sizeof(filebuffer[0]), 
    sizeof(filebuffer)/sizeof(filebuffer[0]), filePtr);
    fread will return the number of bytes it reads on success so for your third argument use an unsigned int so you can check if it was read successfully, in this case again BUFSIZ, and your second argument just the sizeof(data type)


    Code:
    		fclose(filePtr);
    	}
    	else
    	{
    		printf("Sort: Could not read filename :%s\n",fileName);
    		exit(1);
    	}
    }
    always check to make sure flose closed properly, anything can go wrong
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  12. #12
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    Plus im also thinking there is a much better way to do this then my approach.
    This is just one of about three different approaches that I can think of to resolve your problem. I haven't tested it thoroughly. I'll let that up to you. Also, there is an excellent description of binary trees in (I believe) the FAQs area. It would behoove you to read those binary tree articles in order to understand the code.

    Example to sort one file: Sort input.txt input.txt
    This sorts one file the input.txt file.

    Also, you'll have to flesh out the error checking such as checking for valid fopen's etc.

    Please let me know if you find any problems.

    Have fun

    Bob

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    #define LINELENGTH 128
    
    typedef struct SBinaryTree
    {
        char *SBinaryTreeData;
        struct SBinaryTree *SBinaryTreeLeft;
        struct SBinaryTree *SBinaryTreeRight;
    } nBinaryTreeNode;
    
    nBinaryTreeNode *CreateBTNode (char *SBinaryTreeData)
    {
        nBinaryTreeNode *nTempNode = (nBinaryTreeNode *) malloc (sizeof (nBinaryTreeNode));
    
        nTempNode->SBinaryTreeData = (char *) calloc (LINELENGTH, sizeof (char));
        strcpy (nTempNode->SBinaryTreeData, SBinaryTreeData);
        nTempNode->SBinaryTreeLeft = NULL;
        nTempNode->SBinaryTreeRight = NULL;
        return nTempNode;
    }
    
    nBinaryTreeNode *AddBTNode (char *line, nBinaryTreeNode *BTreeRootIn)
    {
        if (BTreeRootIn == NULL)
            return CreateBTNode (line);
        if (strcmp (line, BTreeRootIn->SBinaryTreeData) < 0)
            BTreeRootIn->SBinaryTreeLeft = AddBTNode (line, BTreeRootIn->SBinaryTreeLeft);
        else
            BTreeRootIn->SBinaryTreeRight = AddBTNode (line, BTreeRootIn->SBinaryTreeRight);
        return BTreeRootIn;
    }
    
    nBinaryTreeNode *ReadFile (FILE *Inputfp)
    {
        nBinaryTreeNode *BTRoot = NULL;
        char szReadLine[LINELENGTH]= {0};
    
        while (fgets(szReadLine, sizeof(szReadLine), Inputfp) != NULL)
        {
            BTRoot = AddBTNode (szReadLine, BTRoot);
        }
        return BTRoot;
    }
    
    void WriteFile (nBinaryTreeNode *BTRootOut, FILE *Outputfp)
    { 
        if (BTRootOut->SBinaryTreeLeft != NULL)
            WriteFile (BTRootOut->SBinaryTreeLeft, Outputfp);
        // Assumes that lines in Inputfile are terminated with a CR LF
        fprintf (Outputfp, "%s", BTRootOut->SBinaryTreeData);
        if (BTRootOut->SBinaryTreeRight != NULL)
            WriteFile (BTRootOut->SBinaryTreeRight, Outputfp);
    }
    
    void SortFile (char *InFile, char *OutFile)
    {
        FILE *Inputfp = fopen (InFile, "r");
        nBinaryTreeNode *BTRoot = ReadFile (Inputfp);
        fclose (Inputfp);
        FILE *Outputfp = fopen (OutFile, "w");
        WriteFile (BTRoot, Outputfp);
        fclose (Outputfp);
    }
    
    int main (int argc, char **argv)
    {
        if (argc != 3)
            printf ("Usage: %s Unsorted file Sorted file\n", argv[0]);
        else
            SortFile (argv [1], argv [2]);
        return 0;
    }
    Last edited by BobS0327; 10-29-2005 at 09:24 PM. Reason: Forgot to mention error checking

  13. #13
    Registered User
    Join Date
    Oct 2005
    Posts
    24
    Cool, thanks for all the help guys. I got it figured out =). I used a binary tree in the end (thanks bob i nicked your btree code, dont worry i did read the binary tree chapter and understood it).

    here's the final code i got if your intrested.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    /***************************************
    This program shall SORT using a binary tree.
    
    ©2005 Mark Crick
    ****************************************/
    #define MAX 256
    
    typedef struct SBinaryTree
    {
        char *SBinaryTreeData;
        struct SBinaryTree *SBinaryTreeLeft;
        struct SBinaryTree *SBinaryTreeRight;
    } nBinaryTreeNode;
    
    nBinaryTreeNode *CreateBTNode (char *SBinaryTreeData)// Create tree
    {
        nBinaryTreeNode *nTempNode = (nBinaryTreeNode *) malloc (sizeof (nBinaryTreeNode));
    
        nTempNode->SBinaryTreeData = (char *) calloc (MAX, sizeof (char));
        strcpy (nTempNode->SBinaryTreeData, SBinaryTreeData);
        nTempNode->SBinaryTreeLeft = NULL;
        nTempNode->SBinaryTreeRight = NULL;
        return nTempNode;
    }
    
    nBinaryTreeNode *AddBTNode (char *line, nBinaryTreeNode *BTreeRootIn) //Add node to tree
    {
        if (BTreeRootIn == NULL)
            return CreateBTNode (line);
        if (strcmp (line, BTreeRootIn->SBinaryTreeData) < 0)
            BTreeRootIn->SBinaryTreeLeft = AddBTNode (line, BTreeRootIn->SBinaryTreeLeft);
        else
            BTreeRootIn->SBinaryTreeRight = AddBTNode (line, BTreeRootIn->SBinaryTreeRight);
        return BTreeRootIn;
    }
    void WriteFileFromTree(nBinaryTreeNode *BTRootOut , FILE *filePtr)// Recursive method writes file according to tree struct
    {
      	if (BTRootOut->SBinaryTreeLeft != NULL)
    		WriteFileFromTree (BTRootOut->SBinaryTreeLeft,filePtr);
    
    	fprintf (filePtr, "%s", BTRootOut->SBinaryTreeData);
    
    	if (BTRootOut->SBinaryTreeRight != NULL)
            WriteFileFromTree (BTRootOut->SBinaryTreeRight,filePtr);
    }
    void OpenWriteFileFromTree(char *fileName,nBinaryTreeNode *BTRootOut)//Opens file to write to then calls method to write tree to file
    {
    	FILE *filePtr;
    
    	if((filePtr = fopen(fileName,"w")) != NULL)
    	{
    		WriteFileFromTree(BTRootOut,filePtr);
    		if(fclose(filePtr)==EOF)
    		{
    			perror("Sort");
    			exit(1);
    		}
    	}
    	else
    	{
    		fclose(filePtr); //Didnt catch close errors here because there is allready an open error.
    		perror("Sort");	// And code would be the same if there was error or no error
    		exit(1);
    	}
    }
    
    nBinaryTreeNode  *ReadFileToTree(char *fileName)// This will read the text file into the buffer array
    {
      	FILE *filePtr;
    	nBinaryTreeNode *BTRoot = NULL;
    
      	if((filePtr = fopen(fileName,"r")) != NULL)
    	{
        	char szReadLine[MAX]= {0};
        	while (fgets(szReadLine, sizeof(szReadLine), filePtr) != NULL)
    		{
    		    BTRoot = AddBTNode (szReadLine, BTRoot);
    		}
    		if(fclose(filePtr)==EOF)
    		{
    			perror("Sort");
    			exit(1);
    		}
    	}
    	else
    	{
    		fclose(filePtr); //Didnt catch close errors here because there is allready an open error.
    		perror("Sort"); // And code would be the same if there was error or no error
    		exit(1);
    	}
    	return BTRoot;
    }
    int main(int argc, char **argv)
    {
    	if(argc == 2)
    	{
    		nBinaryTreeNode *BTRoot = ReadFileToTree(argv[1]);
    		OpenWriteFileFromTree(argv[1],BTRoot);
    	}
    	else
    	{
    		printf("Sort: Incorrect argument \nSyntax: Sort [file to sort]");
    		exit(1);
    	}
    	printf("Sort.exe wOOt!. \n");
    	return(0);
    }

  14. #14
    Registered User caroundw5h's Avatar
    Join Date
    Oct 2003
    Posts
    751
    you obviously made some changes, so congrats on doing that at least. My two cents...

    Code:
      nBinaryTreeNode *nTempNode = (nBinaryTreeNode *) malloc (sizeof 
    (nBinaryTreeNode));
    malloc doesn't need to be cast in C and shouldn't be.

    Code:
      nTempNode->SBinaryTreeData = (char *) calloc (MAX, sizeof (char));
    i believe it is ditto for calloc. I do like the variety shown i n memory allocation however.

    Code:
    strcpy (nTempNode->SBinaryTreeData, SBinaryTreeData);
    what happens if SBinaryTreeData is more than MAX? you could make the buffer bigger or you could check out strncpy and try that.


    Code:
    	printf("Sort: Incorrect argument \nSyntax: Sort [file to sort]");
    exit(1);
    if argc!=2, we never see this since it just exits. Do you maybe want to add a getchar() there so your user knows whats up?


    as for main
    Code:
    int main(int argc, char **argv)
    {
    	if(argc == 2)
    	{
    		nBinaryTreeNode *BTRoot = ReadFileToTree(argv[1]);
    		OpenWriteFileFromTree(argv[1],BTRoot);
    	}
    	else
    	{
    
    		printf("Sort: Incorrect argument \nSyntax: Sort [file to sort]");
    		exit(1);
    	}
    	printf("Sort.exe wOOt!. \n");
    	return(0);
    }
    I suppose the code after the else block does get executed, but i just find your logic to do so round about, but hey if it works for you who am i to say. I would have done it a bit more straight forward
    Code:
    if(argc == 2)
    	{
    		nBinaryTreeNode *BTRoot = ReadFileToTree(argv[1]);
    		OpenWriteFileFromTree(argv[1],BTRoot);
    		printf("Sort.exe wOOt!. \n");
            getchar();
    	    return(0);
    	}
    Warning: Opinions subject to change without notice

    The C Library Reference Guide
    Understand the fundamentals
    Then have some more fun

  15. #15
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,058
    You've got some good points there. I guess I've been casting malloc for years and just comes as second nature. I would assume this non cast approach is part of the ISO standard?

    Yes, it's very possible to run into trouble with MAX. I got lazy here and just didn't want to get involved with using a dynamic approach. It'd be a good exercise for fatdunky.

    Thanx for keeping me honest.

    Bob

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Beginner Text File Input Question
    By Ruggles in forum C++ Programming
    Replies: 2
    Last Post: 11-12-2006, 02:18 PM
  2. Function is called and I am trying to open a file
    By tommy69 in forum C Programming
    Replies: 88
    Last Post: 05-06-2004, 08:33 AM
  3. Removing text between /* */ in a file
    By 0rion in forum C Programming
    Replies: 2
    Last Post: 04-05-2004, 08:54 AM
  4. Read word from text file (It is an essay)
    By forfor in forum C Programming
    Replies: 7
    Last Post: 05-08-2003, 11:45 AM
  5. Ok, Structs, I need help I am not familiar with them
    By incognito in forum C++ Programming
    Replies: 7
    Last Post: 06-29-2002, 09:45 PM