我正在尝试制作从文件字符中读取的递归函数,但它在 C 中不起作用

I am trying to make recursive function which is reading from file character wise but it's not working in C

我一直在接触使用 C 的递归技术,这是我面临的问题 -

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 ] = '[=10=]';
      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 );

}

如果我把 printf("%s", temp ); 放在我上面提到的 //1// 的地方,那么输出会很好,但是如果我在那里调用函数,它会很明智。

我正在尝试做的是我正在使用 open 系统调用读取文件并将文件传递给上述函数并尝试通过 char.But 读取 char,但没有发生。 请帮助我如何调用逐字逐句输出的函数。

谢谢!!!!

我想做的是制作 tempindex 局部变量。因此,我改变了我的函数调用-

bool FetchInputFromFile(char * temp, size_t * value, int file_dis );

我在函数里面加了一行,就是,

size_t index =*value;

并删除了 memset 调用。

如果我能使这个函数调用更好,请post我。

感谢您的帮助。

我认为这可能是更好的方法

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, &currentChar, ch_size);
    if (currentChar == ' ') 
    {
        nextWord[(*index)] = '[=10=]';              /* 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);
    }
}

(我没有编译这个!)

首先,当您写入字符串时,您需要检查您是否没有溢出缓冲区。您需要确保每个分支 return 都有一个值,或者只有一个 return 语句和 return 一个由不同分支设置的变量。 最重要的是,清楚地格式化你的代码,你写了一个代码,但它被阅读了很多次,所以花点时间添加花括号和制表符。

而且我仍然认为这是一种糟糕的阅读方式,但我认为这样做是有原因的。