簡體   English   中英

使用strtok()和strcmp()的分段錯誤錯誤

[英]Segmentation fault error using strtok() and strcmp()

我正在嘗試制作簡單的C程序,該程序逐行檢查Linux密碼文件,以命令行參數提供的用戶名開頭的行。 每行包含幾個以冒號分隔的標記。 第一個令牌是用戶名,第二個令牌是無關的,第三個令牌是需要打印的用戶ID(UID)號,第四個令牌是也需要打印的組ID號(GID)。

使用一些打印測試並在線搜索解決方案,我認為將令牌變量分配給我的第一個strtok調用后,令牌變量仍然為NULL(此時令牌的printf不會打印任何內容)。 然后,使用strcmp將NULL令牌與產生分段錯誤錯誤的用戶名進行比較。 如果到目前為止我的分析是正確的(由於我是C的新手,那么很可能不是),如何避免/解決此問題,為什么會這樣?

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char **argv)
{
    FILE *pwfile;
    char *userName;
    char buf[1024];
    const char s[2] = ":";
    char *token;
    int ch, number_of_lines = 0;
    int i;

    if(argc != 2)
    {
            perror("must supply a user name");

            return -1;
    }

    pwfile = fopen("/home/c2467/passwd", "r");

    if( pwfile == NULL)
    {
        perror( "error opening password file" );

        return -1;
     }

     userName = argv[1];

     do//loop to determine number of lines in the file
     {
         ch = fgetc(pwfile);
         if(ch == '\n')
         number_of_lines++;
     } while (ch != EOF);

     if(ch != '\n' && number_of_lines != 0)
     {
         number_of_lines++;
     }

     for (i = 0; i <= number_of_lines; i++)//iterates through lines of file
     {

         fgets(buf, 1024, pwfile);//stores line into buf

         if (ferror(pwfile) != 0)//tests error indicator for given stream
         {
             perror("fgets error");
             return 1;
         }

         if (feof(pwfile) == 0)//checks if at end of file
         {
             break;
         }

         token = strtok( buf, s);//stores first token of current line in file

         if( strcmp(token, userName) == 0 )//compares token to user name entered
         {
             token = strtok( NULL, s);//Jumps to 2nd token in line, which is irrelevant so do nothing
             token = strtok( NULL, s);//Jumps to 3rd token which is UID number
             printf( "UID: %s\n", token );
             token = strtok( NULL, s);//Jumps to 4th token which is GID number
             printf( "GID: %s\n", token );
             break;
          }

     }
     fclose(pwfile);

     return 0;
}

您從頭到尾讀取文件以獲取新行數。

但是,您可以重新開始閱讀而無需回到開頭。 這會導致您的fget失敗(在EOF之后讀取)。

您必須致電:

fseek(pwfile, 0 , SEEK_SET);

您還會從for中斷(feof(pwfile) == 0) ,這在文件不在文件末尾的情況下是正確的,這意味着,即使倒帶后,您也將在處理第一個文件之前停止線。

您應該將其更改為:

if (feof(pwfile))

否則,它似乎可以正常工作。 (但是,我個人討厭strtok)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM