如何从main()访问函数变量

时间:2014-03-06 09:12:20

标签: c

我试图在main()中使用这个字符比较功能,而忽略区分大小写。有没有办法从main调用toupper(ch1)和toupper(ch2),这样如果引发-i(不区分大小写),我可以重用代码。

int CharacterCompare( FILE *file1, FILE *file2, char file1name[], char file2name[] )
{
   int ch1, ch2;
   int differ = 0;

   do
   {

    ch1 = fgetc( file1 );
      ch2 = fgetc( file2 );
      differ++;

      if ( feof( file1 ) && !feof( file2 ) )
      {  
         printf( "EOF on %s\n", file1name );
         return 1;         
      }
      else if ( feof( file2 ) && !feof( file1) )
      {
         printf( "EOF on %s\n", file2name );
         return 1;
      }

      if (ch1 != ch2)
      {
         printf( "files differ: char %d\n", differ );
         return 1;
      }     
   } 
   while( ( !feof( file1 ) ) && ( !feof( file2 ) ) && (ch1 == ch2) );

   printf( "files are equal\n" );

   return 0;
}

3 个答案:

答案 0 :(得分:2)

答案很长(未经测试,但您应该明白这一点):

int Compare(char ch1, char ch2, int ignorecase)
{
  if (ignorecase)
  {
    ch1 = toupper(ch1) ;
    ch2 = toupper(ch2) ;
  }

  return ch1 == ch2 ;
}


int CharacterCompare( FILE *file1, FILE *file2, char file1name[], char file2name[],
                      int ignorecase )
{
   int ch1, ch2;
   int differ = 0;

   do
   {
    ch1 = fgetc( file1 );
      ch2 = fgetc( file2 );
      differ++;

      if ( feof( file1 ) && !feof( file2 ) )
      {  
         printf( "EOF on %s\n", file1name );
         return 1;         
      }
      else if ( feof( file2 ) && !feof( file1) )
      {
         printf( "EOF on %s\n", file2name );
         return 1;
      }

      if (Compare(ch1, ch2, ignorecase))
      {
         printf( "files differ: char %d\n", differ );
         return 1;
      }     
   } 
   while( ( !feof( file1 ) ) && ( !feof( file2 ) ) && (ch1 == ch2) );

   printf( "files are equal\n" );

   return 0;
}

主要包括:

ignorecase = argv[1] == "-i" ;
int different = CharacterCompare(f2, f2, name1, name2, ignorecase) ;

答案 1 :(得分:1)

简短(且唯一)的答案是:不,你不能访问在其他函数中本地声明的变量。

而是将不区分大小写作为参数传递给函数。

答案 2 :(得分:1)

通常,如果您需要重用代码,请将其包装在自己的函数中。

在这种情况下,为什么可以从toupper致电main

...

  if (toupper(ch1) != toupper(ch2))
  {
     printf( "files differ: char %d\n", differ );
     return 1;
  }
 ...
  while( ( !feof( file1 ) ) && ( !feof( file2 ) ) && (toupper(ch1) == toupper(ch2)) );

或将不区分大小写的比较包装到函数中:

int caseinvariantcomp(char c1, char c2) {
    return toupper(c1) - toupper(c2);
}

...

  if (caseinvariantcomp(ch1, ch2))
  {
     printf( "files differ: char %d\n", differ );
     return 1;
  }
 ...
  while( ( !feof( file1 ) ) && ( !feof( file2 ) ) && (!caseinvariantcomp(ch1, ch2)) );