printf()仅在我的while循环期间打印空值

时间:2014-09-25 18:45:13

标签: c printf

有人可以解释为什么我在尝试打印字符串的值时会得到:(null)(null)(null)的读数吗?

这是我的代码:

char
translate(char *fileName2)
    {
   char *str1;
   int counted;
   int count;
   int printed;
   int i;
   FILE * fp;
   i = 0;
   count = 0;
   counted = 0;
   printed = 0;
   fp = fopen(fileName2, "r");
   do
    {
       if (!feof(fp)&&counted==0)
         {
              count+=1;
              readToken(fp);
         }
      else
         {
             counted=1;
         } 
    }
    while (counted==0);
     printf("there are %d words in the file %s\n",count,fileName2);
     do 
     {
    if (i<count)
         {
            //Problem here
            printed=0;
            i+=1;
            str1 = readToken(fp); 
            printf("%s ",str1); //THIS IS WHERE THE NULL GETS PRINTED!!
            //free(str1);
         }
      else
         {
            printed=1;
            printf("file has been printed\n");
            printf("value of count here is:%d\n",count);
            printf("value of i here is:%d\n",i);
         } 
      }
     while(counted==1&&printed==0);
   fclose(fp);
   return(0);
    }

我真的不明白为什么当我尝试打印它时它为str1的值给我(null)。可能有更好的方法来做到这一点,但我不是最先进的,所以任何建议都会受到赞赏...谢谢:)

编辑: 这是readToken()

的代码
char *
readToken(FILE *fp)
{
int ch,index;
char *buffer;
int size = 80;

skipWhiteSpace(fp);

ch = fgetc(fp);
if (ch == EOF) return 0;

buffer = allocateMsg(size,"readToken");

index = 0;
while (!isspace(ch))
    {
    if (ch == EOF) break;
    if (index > size - 2)
        {
        ++size;
        buffer = reallocateMsg(buffer,size,"readToken");
        }
    buffer[index] = ch;
    ++index;
    ch = fgetc(fp);
    }

/* push back the character that got us out of this loop */

ungetc(ch,fp);
buffer[index] = '\0';

return buffer;
}

1 个答案:

答案 0 :(得分:0)

您可能想要添加

  rewind(fp);   //you need to reset the file pointer to the beginning. 
在你的第二个while循环之前

     do 
    {
      if (i<count)
      {
        //Problem here
        printed=0;
        i+=1;
        str1 = readToken(fp); 
        printf("%s ",str1); //THIS IS WHERE THE NULL GETS PRINTED!!
        //free(str1);
      }
      else
      {
        printed=1;
        printf("file has been printed\n");
        printf("value of count here is:%d\n",count);
        printf("value of i here is:%d\n",i);
      } 
   }
   while(counted==1&&printed==0);