I have been getting hands on recursive technique using C , here the problem I am facing -
bool FetchInputFromFile(int file_dis ){
// file_dis is the file descriptor which I have used in main with `open` sys call
char ch; //I want to read char wise
size_t ch_size =sizeof(ch );
char temp[30];
size_t index =0;
size_t numread;
//memset(temp, 0, 30 );
numread =read(file_dis, &ch, ch_size );
if(ch == ' ' ){
temp[index ] = '\0';
index =0;
InsertInList(temp ); //calling function with temp
}else temp[index++] = ch;
//1//
//base case and recursive call
if(numread ==0 ) return true;
else if(numread == -1 )return false;
else FetchInputFromFile(file_dis );
}
if I put printf("%s", temp );
where I have mentioned //1//
above then the output is coming fine but if I call function over there , its going character wise.
What I am trying to do is I am reading file with open
sys call and I am passing the file to the above function and trying to read char by char.But, it's not happening.
Please help me how I can call function where the output goes word by word.
THANKS!!!!
I think this might be a better approach
bool FetchInputFromFile(int file_dis, char* nextWord, int* index)
{
#define MAXSTRINGLENGTH (30)
/* file_dis is the file descriptor which I have used in main with `open` sys call */
const size_t ch_size = sizeof(char); /* size of types not variables.*/
char currentChar; /* I want to read char wise*/
size_t readResult;
if (!nextWord)
{ /* Allocate memory for the buffer if there is none */
nextWord = (char*)malloc(sizeof(char) * MAXSTRINGLENGTH);
}
readResult = read(file_dis, ¤tChar, ch_size);
if (currentChar == ' ')
{
nextWord[(*index)] = '\0'; /* Terminate the string*/
InsertInList(nextWord); //calling function with temp */
*index = 0; /* Reset the index to zero to reuse the buffer nextWord*/
}
else if ((*index) < MAXSTRINGLENGTH)
{
nextWord[(*index)++] = currentChar;
//1*/
}
//base case and recursive call*/
if (readResult == 0)
{
if (nextWord) /* Should be a function/macro*/
{
free(nextWord);
nextWord = NULL;
}
return true;
}
else if (readResult == -1)
{
if (nextWord) /* Should be a function/macro*/
{
free(nextWord);
nextWord = NULL;
}
return false;
}
else
{
return FetchInputFromFile(file_dis, nextWord, index);
}
}
(I have not compiled this!)
Firstly when you write to the string you need to check that you don't over flow the buffer. You need to ensure every branch returns a value OR just have a single return statement and return a variable that the different branches set. And most importantly, format you code clearly, you write the code one, but it is read many more times, so take those few moments to add curly braces and tabs.
And I still think this is a bad way to read words, but I assume there is a reason to do it this way.