我试图制作递归函数,这是从文件字符明智地读取,但它不在C中工作

时间:2017-03-24 12:23:42

标签: c linux tail-recursion systems-programming

我一直在使用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 ] = '\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 );

}

如果我将printf("%s", temp );放在我上面提到//1//的位置,那么输出就会好起来但是如果我在那里调用函数,那么它就会明智。

我想要做的是我正在使用open sys调用来读取文件,并且我将文件传递给上面的函数并尝试通过char读取char。但是,它没有发生。 请帮助我如何在逐字输出的情况下调用函数。

感谢!!!!

2 个答案:

答案 0 :(得分:0)

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

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

我在函数中添加了一行,即

size_t index =*value;

并删除了memset来电。

如果我能更好地打电话,请发帖给我。

感谢您的帮助。

答案 1 :(得分:0)

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

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)] = '\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);
    }
}

(我还没编译过这个!)

首先,当你写入字符串时,你需要检查你是否没有过度缓冲。您需要确保每个分支返回一个值或只有一个return语句并返回不同分支设置的变量。 最重要的是,您可以清楚地编写代码格式,编写代码一个,但是它会被读取很多次,所以请花一些时间添加大括号和标签。

我仍然认为这是一种阅读单词的坏方法,但我认为有理由这样做。