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 :)